-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathweb-push-lib.js
407 lines (350 loc) · 13.3 KB
/
web-push-lib.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import url from 'url';
import https from 'https';
import WebPushError from './web-push-error.js';
import * as vapidHelper from './vapid-helper.js';
import * as encryptionHelper from './encryption-helper.js';
import webPushConstants from './web-push-constants.js';
import * as urlBase64Helper from './urlsafe-base64-helper.js';
// Default TTL is four weeks.
const DEFAULT_TTL = 2419200;
let gcmAPIKey = '';
let vapidDetails;
export function WebPushLib() {
}
/**
* When sending messages to a GCM endpoint you need to set the GCM API key
* by either calling setGMAPIKey() or passing in the API key as an option
* to sendNotification().
* @param {string} apiKey The API key to send with the GCM request.
*/
WebPushLib.prototype.setGCMAPIKey = function(apiKey) {
if (apiKey === null) {
gcmAPIKey = null;
return;
}
if (typeof apiKey === 'undefined'
|| typeof apiKey !== 'string'
|| apiKey.length === 0) {
throw new Error('The GCM API Key should be a non-empty string or null.');
}
gcmAPIKey = apiKey;
};
/**
* When making requests where you want to define VAPID details, call this
* method before sendNotification() or pass in the details and options to
* sendNotification.
* @param {string} subject This must be either a URL or a 'mailto:'
* address. For example: 'https://my-site.com/contact' or
* 'mailto: [email protected]'
* @param {string} publicKey The public VAPID key, a URL safe, base64 encoded string
* @param {string} privateKey The private VAPID key, a URL safe, base64 encoded string.
*/
WebPushLib.prototype.setVapidDetails = function(subject, publicKey, privateKey) {
if (arguments.length === 1 && arguments[0] === null) {
vapidDetails = null;
return;
}
vapidHelper.validateSubject(subject);
vapidHelper.validatePublicKey(publicKey);
vapidHelper.validatePrivateKey(privateKey);
vapidDetails = {
subject: subject,
publicKey: publicKey,
privateKey: privateKey
};
};
/**
* To get the details of a request to trigger a push message, without sending
* a push notification call this method.
*
* This method will throw an error if there is an issue with the input.
* @param {PushSubscription} subscription The PushSubscription you wish to
* send the notification to.
* @param {string|Buffer} [payload] The payload you wish to send to the
* the user.
* @param {Object} [options] Options for the GCM API key and
* vapid keys can be passed in if they are unique for each notification you
* wish to send.
* @return {Object} This method returns an Object which
* contains 'endpoint', 'method', 'headers' and 'payload'.
*/
WebPushLib.prototype.generateRequestDetails = function(subscription, payload, options) {
if (!subscription || !subscription.endpoint) {
throw new Error('You must pass in a subscription with at least '
+ 'an endpoint.');
}
if (typeof subscription.endpoint !== 'string'
|| subscription.endpoint.length === 0) {
throw new Error('The subscription endpoint must be a string with '
+ 'a valid URL.');
}
if (payload) {
// Validate the subscription keys
if (typeof subscription !== 'object' || !subscription.keys
|| !subscription.keys.p256dh
|| !subscription.keys.auth) {
throw new Error('To send a message with a payload, the '
+ 'subscription must have \'auth\' and \'p256dh\' keys.');
}
}
let currentGCMAPIKey = gcmAPIKey;
let currentVapidDetails = vapidDetails;
let timeToLive = DEFAULT_TTL;
let extraHeaders = {};
let contentEncoding = webPushConstants.supportedContentEncodings.AES_128_GCM;
let urgency = webPushConstants.supportedUrgency.NORMAL;
let topic;
let proxy;
let agent;
let timeout;
if (options) {
const validOptionKeys = [
'headers',
'gcmAPIKey',
'vapidDetails',
'TTL',
'contentEncoding',
'urgency',
'topic',
'proxy',
'agent',
'timeout'
];
const optionKeys = Object.keys(options);
for (let i = 0; i < optionKeys.length; i += 1) {
const optionKey = optionKeys[i];
if (!validOptionKeys.includes(optionKey)) {
throw new Error('\'' + optionKey + '\' is an invalid option. '
+ 'The valid options are [\'' + validOptionKeys.join('\', \'')
+ '\'].');
}
}
if (options.headers) {
extraHeaders = options.headers;
let duplicates = Object.keys(extraHeaders)
.filter(function (header) {
return typeof options[header] !== 'undefined';
});
if (duplicates.length > 0) {
throw new Error('Duplicated headers defined ['
+ duplicates.join(',') + ']. Please either define the header in the'
+ 'top level options OR in the \'headers\' key.');
}
}
if (options.gcmAPIKey) {
currentGCMAPIKey = options.gcmAPIKey;
}
// Falsy values are allowed here so one can skip Vapid `else if` below and use FCM
if (options.vapidDetails !== undefined) {
currentVapidDetails = options.vapidDetails;
}
if (options.TTL !== undefined) {
timeToLive = Number(options.TTL);
if (timeToLive < 0) {
throw new Error('TTL should be a number and should be at least 0');
}
}
if (options.contentEncoding) {
if ((options.contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM
|| options.contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM)) {
contentEncoding = options.contentEncoding;
} else {
throw new Error('Unsupported content encoding specified.');
}
}
if (options.urgency) {
if ((options.urgency === webPushConstants.supportedUrgency.VERY_LOW
|| options.urgency === webPushConstants.supportedUrgency.LOW
|| options.urgency === webPushConstants.supportedUrgency.NORMAL
|| options.urgency === webPushConstants.supportedUrgency.HIGH)) {
urgency = options.urgency;
} else {
throw new Error('Unsupported urgency specified.');
}
}
if (options.topic) {
if (!urlBase64Helper.validate(options.topic)) {
throw new Error('Unsupported characters set use the URL or filename-safe Base64 characters set');
}
if (options.topic.length > 32) {
throw new Error('use maximum of 32 characters from the URL or filename-safe Base64 characters set');
}
topic = options.topic;
}
if (options.proxy) {
if (typeof options.proxy === 'string'
|| typeof options.proxy.host === 'string') {
proxy = options.proxy;
} else {
console.warn('Attempt to use proxy option, but invalid type it should be a string or proxy options object.');
}
}
if (options.agent) {
if (options.agent instanceof https.Agent) {
if (proxy) {
console.warn('Agent option will be ignored because proxy option is defined.');
}
agent = options.agent;
} else {
console.warn('Wrong type for the agent option, it should be an instance of https.Agent.');
}
}
if (typeof options.timeout === 'number') {
timeout = options.timeout;
}
}
if (typeof timeToLive === 'undefined') {
timeToLive = DEFAULT_TTL;
}
const requestDetails = {
method: 'POST',
headers: {
TTL: timeToLive
}
};
Object.keys(extraHeaders).forEach(function (header) {
requestDetails.headers[header] = extraHeaders[header];
});
let requestPayload = null;
if (payload) {
const encrypted = encryptionHelper
.encrypt(subscription.keys.p256dh, subscription.keys.auth, payload, contentEncoding);
requestDetails.headers['Content-Length'] = encrypted.cipherText.length;
requestDetails.headers['Content-Type'] = 'application/octet-stream';
if (contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM) {
requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_128_GCM;
} else if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) {
requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_GCM;
requestDetails.headers.Encryption = 'salt=' + encrypted.salt;
requestDetails.headers['Crypto-Key'] = 'dh=' + encrypted.localPublicKey.toString('base64url');
}
requestPayload = encrypted.cipherText;
} else {
requestDetails.headers['Content-Length'] = 0;
}
const isGCM = subscription.endpoint.startsWith('https://android.googleapis.com/gcm/send');
const isFCM = subscription.endpoint.startsWith('https://fcm.googleapis.com/fcm/send');
// VAPID isn't supported by GCM hence the if, else if.
if (isGCM) {
if (!currentGCMAPIKey) {
console.warn('Attempt to send push notification to GCM endpoint, '
+ 'but no GCM key is defined. Please use setGCMApiKey() or add '
+ '\'gcmAPIKey\' as an option.');
} else {
requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey;
}
} else if (currentVapidDetails) {
const parsedUrl = url.parse(subscription.endpoint);
const audience = parsedUrl.protocol + '//'
+ parsedUrl.host;
const vapidHeaders = vapidHelper.getVapidHeaders(
audience,
currentVapidDetails.subject,
currentVapidDetails.publicKey,
currentVapidDetails.privateKey,
contentEncoding
);
requestDetails.headers.Authorization = vapidHeaders.Authorization;
if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) {
if (requestDetails.headers['Crypto-Key']) {
requestDetails.headers['Crypto-Key'] += ';'
+ vapidHeaders['Crypto-Key'];
} else {
requestDetails.headers['Crypto-Key'] = vapidHeaders['Crypto-Key'];
}
}
} else if (isFCM && currentGCMAPIKey) {
requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey;
}
requestDetails.headers.Urgency = urgency;
if (topic) {
requestDetails.headers.Topic = topic;
}
requestDetails.body = requestPayload;
requestDetails.endpoint = subscription.endpoint;
if (proxy) {
requestDetails.proxy = proxy;
}
if (agent) {
requestDetails.agent = agent;
}
if (timeout) {
requestDetails.timeout = timeout;
}
return requestDetails;
};
/**
* To send a push notification call this method with a subscription, optional
* payload and any options.
* @param {PushSubscription} subscription The PushSubscription you wish to
* send the notification to.
* @param {string|Buffer} [payload] The payload you wish to send to the
* the user.
* @param {Object} [options] Options for the GCM API key and
* vapid keys can be passed in if they are unique for each notification you
* wish to send.
* @return {Promise} This method returns a Promise which
* resolves if the sending of the notification was successful, otherwise it
* rejects.
*/
WebPushLib.prototype.sendNotification = function(subscription, payload, options) {
let requestDetails;
try {
requestDetails = this.generateRequestDetails(subscription, payload, options);
} catch (err) {
return Promise.reject(err);
}
return new Promise(function(resolve, reject) {
const httpsOptions = {};
const urlParts = url.parse(requestDetails.endpoint);
httpsOptions.hostname = urlParts.hostname;
httpsOptions.port = urlParts.port;
httpsOptions.path = urlParts.path;
httpsOptions.headers = requestDetails.headers;
httpsOptions.method = requestDetails.method;
if (requestDetails.timeout) {
httpsOptions.timeout = requestDetails.timeout;
}
if (requestDetails.agent) {
httpsOptions.agent = requestDetails.agent;
}
if (requestDetails.proxy) {
const { HttpsProxyAgent } = require('https-proxy-agent'); // eslint-disable-line global-require
httpsOptions.agent = new HttpsProxyAgent(requestDetails.proxy);
}
const pushRequest = https.request(httpsOptions, function(pushResponse) {
let responseText = '';
pushResponse.on('data', function(chunk) {
responseText += chunk;
});
pushResponse.on('end', function() {
if (pushResponse.statusCode < 200 || pushResponse.statusCode > 299) {
reject(new WebPushError(
'Received unexpected response code',
pushResponse.statusCode,
pushResponse.headers,
responseText,
requestDetails.endpoint
));
} else {
resolve({
statusCode: pushResponse.statusCode,
body: responseText,
headers: pushResponse.headers
});
}
});
});
if (requestDetails.timeout) {
pushRequest.on('timeout', function() {
pushRequest.destroy(new Error('Socket timeout'));
});
}
pushRequest.on('error', function(e) {
reject(e);
});
if (requestDetails.body) {
pushRequest.write(requestDetails.body);
}
});
};