Exemple #1
0
        private void OnExecute()
        {
            var vapidKeys = VapidHelper.GenerateVapidKeys();

            var publicKey  = $"const vapidPublicKey = '{vapidKeys.PublicKey}';";
            var privateKey = $"const vapidPrivateKey = '{vapidKeys.PrivateKey}';";

            File.WriteAllText("service-worker.js", serviceWorkerFile);
            File.WriteAllText("index.html", indexFile);
            File.WriteAllLines("app.js", new string[] { publicKey, privateKey, appFile });

            var bytes = Convert.FromBase64String(iconFile);

            using (var imageFile = new FileStream("icon.png", FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }

            Console.WriteLine(
                $"\nGenerated!\n\nPublic key: {vapidKeys.PublicKey}\nPrivate key: {vapidKeys.PrivateKey}\n\n" +
                "- Run dotnet serve -o\n" +
                "- Click the Subscribe button\n" +
                "- Copy command from textarea (Send command)\n" +
                "- Paste command into terminal to send push notification\n");
        }
        /// <summary>
        /// Start the push server, this initialized vapid details from a file, if it exists else it will create the vapid details
        /// </summary>
        public static async void Start()
        {
            Console.WriteLine("Started push server");
            // Read Vapid details from cache or create new ones
            if (File.Exists(VapidDetailsFile))
            {
                Details = await ImportVapidDetails();
            }
            else
            {
                Details         = VapidHelper.GenerateVapidKeys();
                Details.Subject = Subject;
                await ExportVapidDetails(Details);
            }

            // Read list of clients from cache or create empty list
            if (File.Exists(ClientsFile))
            {
                Clients = await ImportClients();
            }
            else
            {
                Clients = new List <PushClient>();
                await ExportClients(Clients);
            }
        }
Exemple #3
0
        private void CreateKeys_OnClick(object sender, RoutedEventArgs e)
        {
            VapidDetails keys = VapidHelper.GenerateVapidKeys();

            PrivateKeyTextBox.Text = keys.PrivateKey;
            PublicKeyTextBox.Text  = keys.PublicKey;
        }
        public ActionResult <string> enviar(string pushEndpoint, string p256dh, string auth)
        {
            var keys = VapidHelper.GenerateVapidKeys();

            // "eC8kA5lfrjc:APA91bHHHh3ikNWPa-614pz7FbWdPvCTn01OvkNuas6m-ilwP-U_VPHLd5QPsjL8W5G8gLquoTJd-jUVRDOziyXvxXoeY8ua2sRvt6GnG8WLpFdOkk7SI8_AxFZnlug4t9FOU7S-XjzH"
            pushEndpoint = @"https://fcm.googleapis.com/fcm/send/" + pushEndpoint;
            //p256dh = @"BAGGIn3MC7LZRCFKuRRSjA28bwQRP7mO_9AEr2l7ety-dtSn7Fcw11-aZu5UCOE0C2gVXVEaWkFLu7PWCR1ufGI";
            //auth = @"VKMl5N1lJomQreFUjKlzeQ";

            var subject    = @"mailto:[email protected]";
            var publicKey  = keys.PublicKey;
            var privateKey = keys.PrivateKey;

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "payload", vapidDetails);
            }
            catch (WebPushException exception)
            {
                return(exception.StatusCode.ToString());
            }

            return("OK");
        }
Exemple #5
0
        public void TestGetVapidHeadersSubjectNotAUrlOrMailTo()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate { VapidHelper.GetVapidHeaders(ValidAudience, @"invalid subject", publicKey, privatekey); });
        }
Exemple #6
0
        public void TestGetVapidHeadersAudienceNotAUrl()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate { VapidHelper.GetVapidHeaders(@"invalid audience", ValidSubject, publicKey, privatekey); });
        }
Exemple #7
0
        public void TestGenerateVapidKeysNoCache()
        {
            var keys1 = VapidHelper.GenerateVapidKeys();
            var keys2 = VapidHelper.GenerateVapidKeys();

            Assert.NotEqual(keys1.PublicKey, keys2.PublicKey);
            Assert.NotEqual(keys1.PrivateKey, keys2.PrivateKey);
        }
Exemple #8
0
        /// <summary>
        ///     When marking requests where you want to define VAPID details, call this method
        ///     before sendNotifications() or pass in the details and options to
        ///     sendNotification.
        /// </summary>
        /// <param name="vapidDetails"></param>
        public void SetVapidDetails(VapidDetails vapidDetails)
        {
            VapidHelper.ValidateSubject(vapidDetails.Subject);
            VapidHelper.ValidatePublicKey(vapidDetails.PublicKey);
            VapidHelper.ValidatePrivateKey(vapidDetails.PrivateKey);

            _vapidDetails = vapidDetails;
        }
Exemple #9
0
        public IActionResult GenerateKeys()
        {
            var keys = VapidHelper.GenerateVapidKeys();

            ViewBag.PublicKey  = keys.PublicKey;
            ViewBag.PrivateKey = keys.PrivateKey;
            return(View());
        }
Exemple #10
0
        public void TestGetVapidHeadersSubjectNotAUrlOrMailTo()
        {
            var publicKey  = TestPublicKey;
            var privateKey = TestPrivateKey;

            Assert.ThrowsException <ArgumentException>(
                delegate { VapidHelper.GetVapidHeaders(ValidAudience, @"invalid subject", publicKey, privateKey); });
        }
Exemple #11
0
        public void TestGetVapidHeadersInvalidPublicKey()
        {
            var publicKey  = UrlBase64.Encode(new byte[1]);
            var privateKey = UrlBase64.Encode(new byte[32]);

            Assert.ThrowsException <ArgumentException>(
                delegate { VapidHelper.GetVapidHeaders(ValidAudience, ValidSubject, publicKey, privateKey); });
        }
Exemple #12
0
 public async Task <IActionResult> GetKeysAsync(CancellationToken cancellationToken = default)
 {
     return(await Task.Run(() =>
     {
         VapidDetails keys = VapidHelper.GenerateVapidKeys();
         return Ok(keys);
     }, cancellationToken).ConfigureAwait(false));
 }
Exemple #13
0
 public string GetKey()
 {
     if (_keys == null)
     {
         _keys = VapidHelper.GenerateVapidKeys();
     }
     return(_keys.PublicKey);
 }
Exemple #14
0
        public void TestGenerateVapidKeysNoCache()
        {
            VapidDetails keys1 = VapidHelper.GenerateVapidKeys();
            VapidDetails keys2 = VapidHelper.GenerateVapidKeys();

            Assert.AreNotEqual(keys1.PublicKey, keys2.PublicKey);
            Assert.AreNotEqual(keys1.PrivateKey, keys2.PrivateKey);
        }
Exemple #15
0
        /// <summary>
        /// https://github.com/web-push-libs/web-push-csharp
        /// </summary>
        static void GenerateAndPrintVapidKeys()
        {
            VapidDetails vapidKeys = VapidHelper.GenerateVapidKeys();

            // Prints 2 URL Safe Base64 Encoded Strings
            Console.WriteLine("Public {0}", vapidKeys.PublicKey);
            Console.WriteLine("Private {0}", vapidKeys.PrivateKey);
        }
Exemple #16
0
        public void TestGetVapidHeaders()
        {
            var publicKey  = TestPublicKey;
            var privateKey = TestPrivateKey;
            var headers    = VapidHelper.GetVapidHeaders(ValidAudience, ValidSubject, publicKey, privateKey);

            Assert.IsTrue(headers.ContainsKey(@"Authorization"));
            Assert.IsTrue(headers.ContainsKey(@"Crypto-Key"));
        }
Exemple #17
0
        public void TestGenerateVapidKeys()
        {
            var keys       = VapidHelper.GenerateVapidKeys();
            var publicKey  = UrlBase64.Decode(keys.PublicKey);
            var privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Exemple #18
0
        public void TestGetVapidHeaders()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);
            Dictionary <string, string> headers = VapidHelper.GetVapidHeaders(VALID_AUDIENCE, VALID_SUBJECT, publicKey, privatekey);

            Assert.IsTrue(headers.ContainsKey("Authorization"));
            Assert.IsTrue(headers.ContainsKey("Crypto-Key"));
        }
Exemple #19
0
        static void Main(string[] args)
        {
            var vapidkeys = VapidHelper.GenerateVapidKeys();

            Console.WriteLine($"Public Key : {vapidkeys.PublicKey}");
            Console.WriteLine($"Private key : {vapidkeys.PrivateKey}");

            Console.Read();
        }
Exemple #20
0
        public void TestGetVapidHeaders()
        {
            var publicKey  = UrlBase64.Encode(new byte[65]);
            var privatekey = UrlBase64.Encode(new byte[32]);
            var headers    = VapidHelper.GetVapidHeaders(ValidAudience, ValidSubject, publicKey, privatekey);

            Assert.True(headers.ContainsKey(@"Authorization"));
            Assert.True(headers.ContainsKey(@"Crypto-Key"));
        }
Exemple #21
0
        public void TestGenerateVapidKeys()
        {
            VapidDetails keys = VapidHelper.GenerateVapidKeys();

            byte[] publicKey  = UrlBase64.Decode(keys.PublicKey);
            byte[] privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Exemple #22
0
 public ChatController(ILogger <ChatController> logger)
 {
     _logger           = logger;
     _client           = new WebPushClient();
     vapidKeys         = VapidHelper.GenerateVapidKeys();
     vapidKeys.Subject = "mailto:[email protected]";
     _logger.LogDebug($"Public {vapidKeys.PublicKey}");
     _logger.LogDebug($"Private {vapidKeys.PrivateKey}");
     _logger.LogDebug($"Subject {vapidKeys.Subject}");
 }
Exemple #23
0
        public void TestGetVapidHeadersInvalidPublicKey()
        {
            string publicKey  = UrlBase64.Encode(new byte[1]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders(VALID_AUDIENCE, VALID_SUBJECT, publicKey, privatekey);
            });
        }
 public ActionResult <string> VapidPublicKey()
 {
     if (string.IsNullOrEmpty(_config.Value.PrivateKey))
     {
         var pair = VapidHelper.GenerateVapidKeys();
         _config.Value.PrivateKey = pair.PrivateKey;
         _config.Value.PublicKey  = pair.PublicKey;
         _configurationStore.Store(_config.Value);
     }
     return(Ok(_config.Value.PublicKey));
 }
Exemple #25
0
        public void TestGetVapidHeadersSubjectNotAUrlOrMailTo()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders(VALID_AUDIENCE, "invalid subject", publicKey, privatekey);
            });
        }
Exemple #26
0
        public void TestGetVapidHeadersAudienceNotAUrl()
        {
            string publicKey  = UrlBase64.Encode(new byte[65]);
            string privatekey = UrlBase64.Encode(new byte[32]);

            Assert.Throws(typeof(ArgumentException),
                          delegate
            {
                VapidHelper.GetVapidHeaders("invalid audience", VALID_SUBJECT, publicKey, privatekey);
            });
        }
Exemple #27
0
        public void TestGetVapidHeadersAudienceNotAUrl()
        {
            var publicKey  = TestPublicKey;
            var privateKey = TestPrivateKey;

            Assert.ThrowsException <ArgumentException>(
                delegate
            {
                VapidHelper.GetVapidHeaders("invalid audience", ValidSubjectMailto, publicKey, privateKey);
            });
        }
Exemple #28
0
        public void TestExpirationInPastExceptions()
        {
            var publicKey  = TestPublicKey;
            var privateKey = TestPrivateKey;

            Assert.ThrowsException <ArgumentException>(
                delegate
            {
                VapidHelper.GetVapidHeaders(ValidAudience, ValidSubjectMailto, publicKey,
                                            privateKey, 1552715607);
            });
        }
        public IActionResult GenerateKeys()
        {
            VapidHelper.ValidateSubject("mailto:[email protected]");
            var keys = VapidHelper.GenerateVapidKeys();

            VapidHelper.ValidatePublicKey(keys.PublicKey);
            VapidHelper.ValidatePrivateKey(keys.PrivateKey);

            ViewBag.PublicKey  = keys.PublicKey;
            ViewBag.PrivateKey = keys.PrivateKey;
            return(View());
        }
        /// <summary>
        /// Sets the vapid details.
        /// </summary>
        /// <param name="p_options">Web push options.</param>
        private async Task SetVapidDetails(IOptions <WebPushOptions> p_options)
        {
            bool   v_validSubject = true;
            string v_vapidSubject;
            string v_vapidPublicKey;
            string v_vapidPrivateKey;

            try
            {
                VapidHelper.ValidateSubject(p_options.Value.VapidSubject);
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "Vapid subject is not valid");
                v_validSubject = false;
            }

            if (!v_validSubject && String.IsNullOrWhiteSpace(GcmAPIKey))
            {
                throw new ApplicationException("You must set a valid vapid subject or GCM API Key");
            }

            if (v_validSubject)
            {
                v_vapidSubject = p_options.Value.VapidSubject;

                try
                {
                    VapidHelper.ValidatePublicKey(p_options.Value.VapidPublicKey);
                    VapidHelper.ValidatePrivateKey(p_options.Value.VapidPrivateKey);

                    v_vapidPublicKey  = p_options.Value.VapidPublicKey;
                    v_vapidPrivateKey = p_options.Value.VapidPrivateKey;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Your Vapid keys are not valid. Using auto generated keys.");

                    var v_tempVapid = VapidHelper.GenerateVapidKeys();
                    v_vapidPublicKey  = v_tempVapid.PublicKey;
                    v_vapidPrivateKey = v_tempVapid.PrivateKey;

                    Logger.LogInformation("Flushing existing devices");
                    IEnumerable <Device> v_devices = this.DbContext.Devices;

                    this.DbContext.RemoveRange(v_devices);
                    await this.DbContext.SaveChangesAsync();
                }

                VapidDetails = new VapidDetails(v_vapidSubject, v_vapidPublicKey, v_vapidPrivateKey);
            }
        }