96 lines
2.3 KiB
TypeScript
96 lines
2.3 KiB
TypeScript
|
|
import { VapidKeys } from './VapidKeys.js';
|
|
import jwt from 'jsonwebtoken';
|
|
import crypto from 'crypto';
|
|
import DBService from './db.js';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
|
|
export interface VapidKeyData {
|
|
publicKey: string;
|
|
privateKey: string;
|
|
}
|
|
|
|
class VapidService {
|
|
private static instance: VapidService;
|
|
private dbService: DBService = DBService.getInstance();
|
|
|
|
|
|
private constructor() {
|
|
}
|
|
|
|
|
|
public static getInstance(): VapidService {
|
|
if (!VapidService.instance) {
|
|
VapidService.instance = new VapidService();
|
|
}
|
|
return VapidService.instance;
|
|
}
|
|
|
|
|
|
public async createVAPIDKeys(): Promise<VapidKeys> {
|
|
let result = new VapidKeys();
|
|
if ( this.dbService.isReady ) {
|
|
const keys = this.generateVAPIDKeys();
|
|
await this.dbService.saveVapidKeys(keys['publicKey'], keys['privateKey']);
|
|
|
|
} else {
|
|
console.log(__filename, "Database is not ready.");
|
|
|
|
}
|
|
return result;
|
|
}
|
|
|
|
|
|
private generateVAPIDKeys(): VapidKeyData {
|
|
const ecdh = crypto.createECDH('prime256v1');
|
|
ecdh.generateKeys();
|
|
const result = {
|
|
publicKey: ecdh.getPublicKey().toString('base64'),
|
|
privateKey: ecdh.getPrivateKey().toString('base64')
|
|
};
|
|
return result;
|
|
}
|
|
|
|
/*
|
|
private async addVapidKeys(vapidkeys: VapidKeyData): Promise<VapidKeys> {
|
|
let result = new VapidKeys();
|
|
const keys = await this.getVapidKeys();
|
|
|
|
if (keys.length == 1 && typeof(keys[0].publicKey) == "undefined" ) {
|
|
result = await this.dbService.saveVapidKeys(vapidkeys.publicKey, vapidkeys.privateKey);
|
|
}
|
|
return result;
|
|
}
|
|
*/
|
|
|
|
async getVapidKeys(): Promise<VapidKeys[]> {
|
|
let result = await this.dbService.getVapidKeys();
|
|
return result;
|
|
}
|
|
|
|
|
|
async createVapidAuthHeader(endpoint: string, expiration: number, subject: string): Promise<{ 'Authorization': string, 'Crypto-Key': string }> {
|
|
const { publicKey, privateKey } = await this.getVapidKeys()[0];
|
|
|
|
const jwtInfo = {
|
|
aud: new URL(endpoint).origin,
|
|
exp: Math.floor((Date.now() / 1000) + expiration),
|
|
sub: subject
|
|
};
|
|
|
|
const jwtToken = jwt.sign(jwtInfo, privateKey, { algorithm: 'ES256' });
|
|
|
|
return {
|
|
'Authorization': `vapid t=${jwtToken}, k=${publicKey}`,
|
|
'Crypto-Key': publicKey
|
|
};
|
|
}
|
|
}
|
|
|
|
(async ()=> {
|
|
|
|
})();
|
|
|
|
export default VapidService; |