Updates but not quite ready to test

This commit is contained in:
Matthew Raymer
2023-08-09 19:22:55 +08:00
parent 30a6c956d1
commit 3be533727a
7 changed files with 280 additions and 237 deletions

View File

@@ -2,7 +2,7 @@ import fetch from 'node-fetch';
import * as crypto from 'crypto';
import { ec as EC } from 'elliptic';
class WebPushSender {
export class WebPushSender {
private ec = new EC('prime256v1');
private vapidPrivateKey: string;
@@ -34,8 +34,7 @@ class WebPushSender {
return Buffer.concat([cipher.update(payload, 'utf8'), cipher.final()]);
}
private generateVapidToken(senderKeys, endpoint: string) {
const vapidPublicKey = senderKeys.getPublic().encode('hex');
private generateVapidToken(endpoint: string) {
const tokenPayload = {
aud: endpoint,
exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // 24 hours
@@ -53,7 +52,7 @@ class WebPushSender {
const sharedSecret = this.deriveSharedSecret(senderKeys, subscription.keys.p256dh);
const contentEncryptionKey = this.generateContentEncryptionKeys(sharedSecret, subscription.keys.auth);
const encryptedPayload = this.encryptPayload(contentEncryptionKey, payload);
const vapidToken = this.generateVapidToken(senderKeys, subscription.endpoint);
const vapidToken = this.generateVapidToken(subscription.endpoint);
const headers = {
'Content-Encoding': 'aes128gcm',
@@ -65,17 +64,3 @@ class WebPushSender {
}
}
// Usage example
const vapidPrivateKey = 'YOUR_PRIVATE_VAPID_KEY';
const sender = new WebPushSender(vapidPrivateKey);
const subscription = {
endpoint: 'https://example.pushservice.com/some-id',
keys: {
p256dh: 'BIPULBIpUL...',
auth: 'eHl6...',
},
};
sender.sendPushNotification(subscription, 'Your Push Payload Here')
.then(response => console.log('Push message sent successfully:', response))
.catch(error => console.error('Failed to send push message:', error));

View File

@@ -4,14 +4,16 @@ import bodyParser from 'body-parser';
import { Request, Response } from 'express';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import { WebPushSender } from './WebPushSender'; // Import from previous example
import { WebPushSender } from './WebPushSender.js';
class PushService {
private app = express();
private db: any;
private sender: WebPushSender;
private port: number;
constructor(private port: number, private vapidPrivateKey: string) {
constructor(port: number, vapidPrivateKey: string) {
this.port = port;
this.sender = new WebPushSender(vapidPrivateKey);
this.app.use(bodyParser.json());
@@ -62,11 +64,5 @@ class PushService {
}
}
// Usage example
const pushService = new PushService(3000, 'YOUR_PRIVATE_VAPID_KEY');
pushService.start();
// Example of sending a notification
pushService.sendNotification('p256dh_value_here', 'Your Push Payload Here')
.then(() => console.log('Notification sent successfully'))
.catch((error) => console.error('Failed to send notification:', error));