Skip to content

Commit

Permalink
feat: Use subscription.endpoint to get the apikey
Browse files Browse the repository at this point in the history
 - if no apikey returned use default vapid Authorization
  • Loading branch information
frankpagan committed Sep 28, 2023
1 parent 0267c19 commit 5fdb66d
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,14 @@ class CoCreateNotification {
// Other optional options can be included here
};

const jwt = webpush.generateRequestDetails(subscription, payload, tokenOptions);
const jwt = webpush.generateRequestDetails(subscription.endpoint, payload, tokenOptions);
const apiKey = getAPIKeyForEndpoint(subscrption.endpoint);


const options = {
method: 'POST',
headers: {
'Authorization': `Bearer ${jwt.headers.Authorization}`,
'Authorization': `Bearer ${apiKey || jwt.headers.Authorization}`,
'Content-Type': 'application/json',
},
};
Expand All @@ -162,6 +164,26 @@ class CoCreateNotification {
pushRequest.end();
}

getAPIKeyForEndpoint(endpoint) {
// Define the mapping of browser endpoints to API keys
const browserEndpointsAndAPIKeys = {
'https://fcm.googleapis.com/': 'yourFCMApiKey',
'https://updates.push.services.mozilla.com/wpush/v2/': 'yourMozillaPushServiceApiKey',
'https://api.push.apple.com/': 'yourAPNsApiKey', // For Safari on Mac
'https://api.sandbox.push.apple.com/': 'yourAPNsDevApiKey', // For Safari on iOS (Development)
'https://api.push.apple.com/': 'yourAPNsProdApiKey', // For Safari on iOS (Production)
// Add more browser endpoints and their API keys as needed
};

// Iterate through the keys in the mapping
for (const browserEndpoint of Object.keys(browserEndpointsAndAPIKeys)) {
if (endpoint.startsWith(browserEndpoint)) {
// Return the associated API key if the endpoint starts with a known browser endpoint
return browserEndpointsAndAPIKeys[browserEndpoint];
}
}
}

generateVapidKeys() {
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096, // Choose an appropriate key length
Expand Down

0 comments on commit 5fdb66d

Please sign in to comment.