Skip to content

Commit

Permalink
Changed from commonJS module to ESM.
Browse files Browse the repository at this point in the history
  • Loading branch information
senbar committed Jan 8, 2024
1 parent f4ba922 commit 7aa7597
Show file tree
Hide file tree
Showing 22 changed files with 812 additions and 854 deletions.
7 changes: 5 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"env": {
"es6": true
},
"parserOptions": {
"sourceType": "module"
},
"rules": {
"no-var": 2,
"no-const-assign": 2,
Expand All @@ -11,12 +14,12 @@
"vars-on-top": 0,
"no-use-before-define": 0,
"space-before-function-paren": 0,
"max-len": [1, 120, 2, {"ignoreComments": true, "ignoreUrls": true}],
"max-len": [1, 120, 2, { "ignoreComments": true, "ignoreUrls": true }],
"no-param-reassign": 0,
"quote-props": 0,
"wrap-iife": [2, "inside"],
"import/no-unresolved": 0,
"indent": 0,
"no-buffer-constructor": 0, // We still support Node v4.
"no-buffer-constructor": 0 // We still support Node v4.
}
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"name": "web-push",
"version": "3.6.6",
"description": "Web Push library for Node.js",
"main": "src/index.js",
"type": "module",
"exports": "./src/index.js",
"bin": {
"web-push": "src/cli.js"
},
Expand Down
68 changes: 35 additions & 33 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
#! /usr/bin/env node
/* eslint consistent-return:0 */

'use strict';

const webPush = require('../src/index.js');
import * as webPush from '../src/index.js';
import minimist from 'minimist';

const printUsageDetails = () => {
const actions = [
Expand Down Expand Up @@ -50,9 +48,9 @@ const generateVapidKeys = returnJson => {
} else {
const outputLine = '\n=======================================\n';
outputText = outputLine + '\n'
+ 'Public Key:\n' + vapidKeys.publicKey + '\n\n'
+ 'Private Key:\n' + vapidKeys.privateKey + '\n'
+ outputLine;
+ 'Public Key:\n' + vapidKeys.publicKey + '\n\n'
+ 'Private Key:\n' + vapidKeys.privateKey + '\n'
+ outputLine;
}

console.log(outputText);
Expand Down Expand Up @@ -80,7 +78,7 @@ const sendNotification = args => {
options.TTL = args.ttl;
}

if (argv['vapid-subject'] || argv['vapid-pubkey'] || argv['vapid-pvtkey']) {
if (args['vapid-subject'] || args['vapid-pubkey'] || args['vapid-pvtkey']) {
options.vapidDetails = {
subject: args['vapid-subject'] || null,
publicKey: args['vapid-pubkey'] || null,
Expand All @@ -101,31 +99,35 @@ const sendNotification = args => {
}

webPush.sendNotification(subscription, payload, options)
.then(() => {
console.log('Push message sent.');
}, err => {
console.log('Error sending push message: ');
console.log(err);
})
.then(() => {
process.exit(0);
});
.then(() => {
console.log('Push message sent.');
}, err => {
console.log('Error sending push message: ');
console.log(err);
})
.then(() => {
process.exit(0);
});
};

const action = process.argv[2];
const argv = require('minimist')(process.argv.slice(3));
switch (action) {
case 'send-notification':
if (!argv.endpoint) {
return printUsageDetails();
}
const executeCliAction = () => {
const action = process.argv[2];
const argv = minimist(process.argv.slice(3));
switch (action) {
case 'send-notification':
if (!argv.endpoint) {
return printUsageDetails();
}

sendNotification(argv);
break;
case 'generate-vapid-keys':
generateVapidKeys(argv.json || false);
break;
default:
printUsageDetails();
break;
}
};

sendNotification(argv);
break;
case 'generate-vapid-keys':
generateVapidKeys(argv.json || false);
break;
default:
printUsageDetails();
break;
}
executeCliAction();
16 changes: 5 additions & 11 deletions src/encryption-helper.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
'use strict';
import crypto from 'crypto';
import ece from 'http_ece';

const crypto = require('crypto');
const ece = require('http_ece');

const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
export function encrypt(userPublicKey, userAuth, payload, contentEncoding) {
if (!userPublicKey) {
throw new Error('No user public key provided for encryption.');
}
Expand All @@ -26,7 +24,7 @@ const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {

if (Buffer.from(userAuth, 'base64url').length < 16) {
throw new Error('The subscription auth key should be at least 16 '
+ 'bytes long');
+ 'bytes long');
}

if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
Expand Down Expand Up @@ -55,8 +53,4 @@ const encrypt = function(userPublicKey, userAuth, payload, contentEncoding) {
salt: salt,
cipherText: cipherText
};
};

module.exports = {
encrypt: encrypt
};
}
37 changes: 20 additions & 17 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
'use strict';

const vapidHelper = require('./vapid-helper.js');
const encryptionHelper = require('./encryption-helper.js');
const WebPushLib = require('./web-push-lib.js');
const WebPushError = require('./web-push-error.js');
const WebPushConstants = require('./web-push-constants.js');
import { getVapidHeaders, generateVAPIDKeys } from './vapid-helper.js';
import { encrypt } from './encryption-helper.js';
import { WebPushLib } from './web-push-lib.js';
import WebPushError from './web-push-error.js';
import WebPushConstants from './web-push-constants.js';

const webPush = new WebPushLib();

module.exports = {
WebPushError: WebPushError,
supportedContentEncodings: WebPushConstants.supportedContentEncodings,
encrypt: encryptionHelper.encrypt,
getVapidHeaders: vapidHelper.getVapidHeaders,
generateVAPIDKeys: vapidHelper.generateVAPIDKeys,
setGCMAPIKey: webPush.setGCMAPIKey,
setVapidDetails: webPush.setVapidDetails,
generateRequestDetails: webPush.generateRequestDetails,
sendNotification: webPush.sendNotification.bind(webPush)
const { supportedContentEncodings } = WebPushConstants;
const { setGCMAPIKey, setVapidDetails, generateRequestDetails } = webPush;
const sendNotification = webPush.sendNotification.bind(webPush);

// Exporting variables and functions
export {
WebPushError,
supportedContentEncodings,
encrypt, // renaming for clarity
getVapidHeaders,
generateVAPIDKeys,
setGCMAPIKey,
setVapidDetails,
generateRequestDetails,
sendNotification
};
8 changes: 1 addition & 7 deletions src/urlsafe-base64-helper.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
'use strict';

/**
* @param {string} base64
* @returns {boolean}
*/
function validate(base64) {
export function validate(base64) {
return /^[A-Za-z0-9\-_]+$/.test(base64);
}

module.exports = {
validate: validate
};
50 changes: 19 additions & 31 deletions src/vapid-helper.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
'use strict';
import crypto from 'crypto';
import asn1 from 'asn1.js';
import jws from 'jws';
import { URL } from 'url';

const crypto = require('crypto');
const asn1 = require('asn1.js');
const jws = require('jws');
const { URL } = require('url');

const WebPushConstants = require('./web-push-constants.js');
const urlBase64Helper = require('./urlsafe-base64-helper');
import WebPushConstants from './web-push-constants.js';
import * as urlBase64Helper from './urlsafe-base64-helper.js';

/**
* DEFAULT_EXPIRATION is set to seconds in 12 hours
Expand All @@ -16,7 +14,7 @@ const DEFAULT_EXPIRATION_SECONDS = 12 * 60 * 60;
// Maximum expiration is 24 hours according. (See VAPID spec)
const MAX_EXPIRATION_SECONDS = 24 * 60 * 60;

const ECPrivateKeyASN = asn1.define('ECPrivateKey', function() {
const ECPrivateKeyASN = asn1.define('ECPrivateKey', function () {
this.seq().obj(
this.key('version').int(),
this.key('privateKey').octstr(),
Expand All @@ -37,7 +35,7 @@ function toPEM(key) {
});
}

function generateVAPIDKeys() {
export function generateVAPIDKeys() {
const curve = crypto.createECDH('prime256v1');
curve.generateKeys();

Expand Down Expand Up @@ -65,14 +63,14 @@ function generateVAPIDKeys() {
};
}

function validateSubject(subject) {
export function validateSubject(subject) {
if (!subject) {
throw new Error('No subject set in vapidDetails.subject.');
}

if (typeof subject !== 'string' || subject.length === 0) {
throw new Error('The subject value must be a string containing an https: URL or '
+ 'mailto: address. ' + subject);
+ 'mailto: address. ' + subject);
}

let subjectParseResult = null;
Expand All @@ -88,17 +86,17 @@ function validateSubject(subject) {
console.warn('Vapid subject points to a localhost web URI, which is unsupported by '
+ 'Apple\'s push notification server and will result in a BadJwtToken error when '
+ 'sending notifications.');
}
}
}

function validatePublicKey(publicKey) {
export function validatePublicKey(publicKey) {
if (!publicKey) {
throw new Error('No key set vapidDetails.publicKey');
}

if (typeof publicKey !== 'string') {
throw new Error('Vapid public key is must be a URL safe Base 64 '
+ 'encoded string.');
+ 'encoded string.');
}

if (!urlBase64Helper.validate(publicKey)) {
Expand All @@ -112,14 +110,14 @@ function validatePublicKey(publicKey) {
}
}

function validatePrivateKey(privateKey) {
export function validatePrivateKey(privateKey) {
if (!privateKey) {
throw new Error('No key set in vapidDetails.privateKey');
}

if (typeof privateKey !== 'string') {
throw new Error('Vapid private key must be a URL safe Base 64 '
+ 'encoded string.');
+ 'encoded string.');
}

if (!urlBase64Helper.validate(privateKey)) {
Expand All @@ -141,7 +139,7 @@ function validatePrivateKey(privateKey) {
* @param {Number} numSeconds Number of seconds to be added
* @return {Number} Future expiration in seconds
*/
function getFutureExpirationTimestamp(numSeconds) {
export function getFutureExpirationTimestamp(numSeconds) {
const futureExp = new Date();
futureExp.setSeconds(futureExp.getSeconds() + numSeconds);
return Math.floor(futureExp.getTime() / 1000);
Expand All @@ -153,7 +151,7 @@ function getFutureExpirationTimestamp(numSeconds) {
*
* @param {Number} expiration Expiration seconds from Epoch to be validated
*/
function validateExpiration(expiration) {
export function validateExpiration(expiration) {
if (!Number.isInteger(expiration)) {
throw new Error('`expiration` value must be a number');
}
Expand Down Expand Up @@ -184,14 +182,14 @@ function validateExpiration(expiration) {
* @return {Object} Returns an Object with the Authorization and
* 'Crypto-Key' values to be used as headers.
*/
function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) {
export function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncoding, expiration) {
if (!audience) {
throw new Error('No audience could be generated for VAPID.');
}

if (typeof audience !== 'string' || audience.length === 0) {
throw new Error('The audience value must be a string containing the '
+ 'origin of a push service. ' + audience);
+ 'origin of a push service. ' + audience);
}

try {
Expand Down Expand Up @@ -243,13 +241,3 @@ function getVapidHeaders(audience, subject, publicKey, privateKey, contentEncodi

throw new Error('Unsupported encoding type specified.');
}

module.exports = {
generateVAPIDKeys: generateVAPIDKeys,
getFutureExpirationTimestamp: getFutureExpirationTimestamp,
getVapidHeaders: getVapidHeaders,
validateSubject: validateSubject,
validatePublicKey: validatePublicKey,
validatePrivateKey: validatePrivateKey,
validateExpiration: validateExpiration
};
4 changes: 1 addition & 3 deletions src/web-push-constants.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
'use strict';

const WebPushConstants = {};

WebPushConstants.supportedContentEncodings = {
Expand All @@ -14,4 +12,4 @@ WebPushConstants.supportedUrgency = {
HIGH: 'high'
};

module.exports = WebPushConstants;
export default WebPushConstants;
8 changes: 3 additions & 5 deletions src/web-push-error.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';
import util from 'util';

function WebPushError(message, statusCode, headers, body, endpoint) {
export default function WebPushError(message, statusCode, headers, body, endpoint) {
Error.captureStackTrace(this, this.constructor);

this.name = this.constructor.name;
Expand All @@ -11,6 +11,4 @@ function WebPushError(message, statusCode, headers, body, endpoint) {
this.endpoint = endpoint;
}

require('util').inherits(WebPushError, Error);

module.exports = WebPushError;
util.inherits(WebPushError, Error);
Loading

0 comments on commit 7aa7597

Please sign in to comment.