• Stars
    star
    374
  • Rank 114,346 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 8 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

webpush, Encryption Utilities for Web Push protocol

WebPush

Code Climate Test Coverage Build Status Gem Version

This gem makes it possible to send push messages to web browsers from Ruby backends using the Web Push Protocol. It supports Message Encryption for Web Push to send messages securely from server to user agent.

Payload is supported by Chrome 50+, Firefox 48+, Edge 79+.

webpush Demo app here (building by Sinatra app).

Installation

Add this line to your application's Gemfile:

gem 'webpush'

And then execute:

$ bundle

Or install it yourself as:

$ gem install webpush

Usage

Sending a web push message to a visitor of your website requires a number of steps:

  1. Your server has (optionally) generated (one-time) a set of Voluntary Application server Identification (VAPID) keys. Otherwise, to send messages through Chrome, you have registered your site through the Google Developer Console and have obtained a GCM sender id and GCM API key from your app settings.
  2. A manifest.json file, linked from your user's page, identifies your app settings.
  3. Also in the user's web browser, a serviceWorker is installed and activated and its pushManager property is subscribed to push events with your VAPID public key, with creates a subscription JSON object on the client side.
  4. Your server uses the webpush gem to send a notification with the subscription obtained from the client and an optional payload (the message).
  5. Your service worker is set up to receive 'push' events. To trigger a desktop notification, the user has accepted the prompt to receive notifications from your site.

Generating VAPID keys

Use webpush to generate a VAPID key that has both a public_key and private_key attribute to be saved on the server side.

# One-time, on the server
vapid_key = Webpush.generate_key

# Save these in your application server settings
vapid_key.public_key
vapid_key.private_key

# Or you can save in PEM format if you prefer
vapid_key.to_pem

Declaring manifest.json

Check out the Web Manifest docs for details on what to include in your manifest.json file. If using VAPID, no app credentials are needed.

{
  "name": "My Website"
}

For Chrome web push, add the GCM sender id to a manifest.json.

{
  "name": "My Website",
  "gcm_sender_id": "1006629465533"
}

The file is served within the scope of your service worker script, like at the root, and link to it somewhere in the <head> tag:

<!-- index.html -->
<link rel="manifest" href="/manifest.json" />

Installing a service worker

Your application javascript must register a service worker script at an appropriate scope (we're sticking with the root).

// application.js
// Register the serviceWorker script at /serviceworker.js from your server if supported
if (navigator.serviceWorker) {
  navigator.serviceWorker.register('/serviceworker.js')
  .then(function(reg) {
     console.log('Service worker change, registered the service worker');
  });
}
// Otherwise, no push notifications :(
else {
  console.error('Service worker is not supported in this browser');
}

Subscribing to push notifications

With VAPID

The VAPID public key you generated earlier is made available to the client as a UInt8Array. To do this, one way would be to expose the urlsafe-decoded bytes from Ruby to JavaScript when rendering the HTML template. (Global variables used here for simplicity).

window.vapidPublicKey = new Uint8Array(<%= Base64.urlsafe_decode64(ENV['VAPID_PUBLIC_KEY']).bytes %>);

Your application javascript uses the navigator.serviceWorker.pushManager to subscribe to push notifications, passing the VAPID public key to the subscription settings.

// application.js
// When serviceWorker is supported, installed, and activated,
// subscribe the pushManager property with the vapidPublicKey
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  serviceWorkerRegistration.pushManager
  .subscribe({
    userVisibleOnly: true,
    applicationServerKey: window.vapidPublicKey
  });
});

Without VAPID

If you will not be sending VAPID details, then there is no need generate VAPID keys, and the applicationServerKey parameter may be omitted from the pushManager.subscribe call.

// application.js
// When serviceWorker is supported, installed, and activated,
// subscribe the pushManager property with the vapidPublicKey
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  serviceWorkerRegistration.pushManager
  .subscribe({
    userVisibleOnly: true
  });
});

Triggering a web push notification

Hook into an client-side or backend event in your app to deliver a push message. The server must be made aware of the subscription. In the example below, we send the JSON generated subscription object to our backend at the "/push" endpoint with a message.

// application.js
// Send the subscription and message from the client for the backend
// to set up a push notification
$(".webpush-button").on("click", (e) => {
  navigator.serviceWorker.ready
  .then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.getSubscription()
    .then((subscription) => {
      $.post("/push", { subscription: subscription.toJSON(), message: "You clicked a button!" });
    });
  });
});

Imagine a Ruby app endpoint that responds to the request by triggering notification through the webpush gem.

# app.rb
# Use the webpush gem API to deliver a push notiifcation merging
# the message, subscription values, and vapid options
post "/push" do
  Webpush.payload_send(
    message: params[:message],
    endpoint: params[:subscription][:endpoint],
    p256dh: params[:subscription][:keys][:p256dh],
    auth: params[:subscription][:keys][:auth],
    vapid: {
      subject: "mailto:[email protected]",
      public_key: ENV['VAPID_PUBLIC_KEY'],
      private_key: ENV['VAPID_PRIVATE_KEY']
    },
    ssl_timeout: 5, # value for Net::HTTP#ssl_timeout=, optional
    open_timeout: 5, # value for Net::HTTP#open_timeout=, optional
    read_timeout: 5 # value for Net::HTTP#read_timeout=, optional
  )
end

Note: the VAPID options should be omitted if the client-side subscription was generated without the applicationServerKey parameter described earlier. You would instead pass the GCM api key along with the api request as shown in the Usage section below.

Receiving the push event

Your /serviceworker.js script may respond to 'push' events. One action it can take is to trigger desktop notifications by calling showNotification on the registration property.

// serviceworker.js
// The serviceworker context can respond to 'push' events and trigger
// notifications on the registration property
self.addEventListener("push", (event) => {
  let title = (event.data && event.data.text()) || "Yay a message";
  let body = "We have received a push message";
  let tag = "push-simple-demo-notification-tag";
  let icon = '/assets/my-logo-120x120.png';

  event.waitUntil(
    self.registration.showNotification(title, { body, icon, tag })
  )
});

Before the notifications can be displayed, the user must grant permission for notifications in a browser prompt, using something like the example below.

// application.js

// Let's check if the browser supports notifications
if (!("Notification" in window)) {
  console.error("This browser does not support desktop notification");
}

// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
  console.log("Permission to receive notifications has been granted");
}

// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
  Notification.requestPermission(function (permission) {
    // If the user accepts, let's create a notification
    if (permission === "granted") {
      console.log("Permission to receive notifications has been granted");
    }
  });
}

If everything worked, you should see a desktop notification triggered via web push. Yay!

Note: if you're using Rails, check out serviceworker-rails, a gem that makes it easier to host serviceworker scripts and manifest.json files at canonical endpoints (i.e., non-digested URLs) while taking advantage of the asset pipeline.

API

With a payload

message = {
  title: "title",
  body: "body",
  icon: "http://example.com/icon.pn"
}

Webpush.payload_send(
  endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
  message: JSON.generate(message),
  p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
  auth: "aW1hcmthcmFpa3V6ZQ==",
  ttl: 600, # optional, ttl in seconds, defaults to 2419200 (4 weeks)
  urgency: 'normal' # optional, it can be very-low, low, normal, high, defaults to normal
)

Without a payload

Webpush.payload_send(
  endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
  p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
  auth: "aW1hcmthcmFpa3V6ZQ=="
)

With VAPID

VAPID details are given as a hash with :subject, :public_key, and :private_key. The :subject is a contact URI for the application server as either a "mailto:" or an "https:" address. The :public_key and :private_key should be passed as the base64-encoded values generated with Webpush.generate_key.

Webpush.payload_send(
  endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
  message: "A message",
  p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
  auth: "aW1hcmthcmFpa3V6ZQ==",
  vapid: {
    subject: "mailto:[email protected]",
    public_key: ENV['VAPID_PUBLIC_KEY'],
    private_key: ENV['VAPID_PRIVATE_KEY']
  }
)

With VAPID in PEM format

This library also supports the PEM format for the VAPID keys:

Webpush.payload_send(
  endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
  message: "A message",
  p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
  auth: "aW1hcmthcmFpa3V6ZQ==",
  vapid: {
    subject: "mailto:[email protected]"
    pem: ENV['VAPID_KEYS']
  }
)

With GCM api key

Webpush.payload_send(
  endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
  message: "A message",
  p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
  auth: "aW1hcmthcmFpa3V6ZQ==",
  api_key: "<GCM API KEY>"
)

ServiceWorker sample

see. https://github.com/zaru/web-push-sample

p256dh and auth generate sample code.

navigator.serviceWorker.ready.then(function(sw) {
  Notification.requestPermission(function(permission) {
    if(permission !== 'denied') {
      sw.pushManager.subscribe({userVisibleOnly: true}).then(function(s) {
        var data = {
          endpoint: s.endpoint,
          p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(s.getKey('p256dh')))).replace(/\+/g, '-').replace(/\//g, '_'),
          auth: btoa(String.fromCharCode.apply(null, new Uint8Array(s.getKey('auth')))).replace(/\+/g, '-').replace(/\//g, '_')
        }
        console.log(data);
      });
    }
  });
});

payloads received sample code.

self.addEventListener("push", function(event) {
  var json = event.data.json();
  self.registration.showNotification(json.title, {
    body: json.body,
    icon: json.icon
  });
});

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/zaru/webpush.

More Repositories

1

mewcam

mewcam is an app that allows you to display a camera with a background dropped on the front of your desktop.
JavaScript
136
star
2

menuffy

menuffy is a status menu application that allows you to open the menu of the current application at hand.
Swift
85
star
3

chatgpt-vscode-ext

TypeScript
47
star
4

chatgpt-zundamon-demo

HTML
44
star
5

Cakephp2_AWS_S3_DataSource

CakePHP2のAmazonWebServices S3のファイルを操作をサポートするデータソースプラグイン
PHP
18
star
6

go-echo-api-test-sample

Go
17
star
7

hotwire-spa-demo

Ruby
12
star
8

itamae-rails

Use the itamae is a recipe to make a rails environment.
Ruby
11
star
9

action_cable-ika-game-sample

IkaGame sample. Use Rails5 ActionCable.
Ruby
9
star
10

serverless-plugin-embedded-env-in-code

JavaScript
9
star
11

LightningQR

LightningQR converts the URL to QR code at high speed. So yes, like a lightning⚡️
Swift
8
star
12

vagrant-rails-chef

Rails development environment setup in Vagrant
Ruby
8
star
13

itamae-plugin-recipe-nginx_build

Ruby
8
star
14

quasar_ssr_firebase_sample

SSR sample, QuasarFramework + FIrebase Functions
JavaScript
8
star
15

jobcan

It is a command that allows you to work in and out at JobCan.
Go
7
star
16

go-wasm-pixelate

Go
7
star
17

vuejs-typescript-sample

vuejs + vuex + typescript sample
JavaScript
6
star
18

web-push-sample

ServiceWorker WebPushNotification sample / demo script
JavaScript
5
star
19

convert-imagemagick-web-simulator

Vue
5
star
20

notify_hub

It displays the notification of GitHub to desktop
Swift
5
star
21

seed_builder

automatically generate seeds
Ruby
4
star
22

pixelated-video

JavaScript
4
star
23

webpush_demo_ruby

WebPush API Demo app (Ruby Sinatra)
HTML
4
star
24

docker-to-minikube

Access the minikube environment of the host from within the Docker container
Shell
4
star
25

go-vuejs-heroku

Go and Vue.js demo app, deploy to Heroku
JavaScript
3
star
26

lightning-qr-reader

TypeScript
3
star
27

itamae-plugin-recipe-zabbix

Ruby
2
star
28

rails-docker

Ruby
2
star
29

create-issue-from-slack

TypeScript
2
star
30

grpc-vue-sample

JavaScript
2
star
31

youtube-api-python

Python
2
star
32

container-builder-local-api

REST API mock server for GCP container-builder-local
Go
2
star
33

vue.tategaki

Tategaki (縦書き) editor component for Vue.js
Vue
2
star
34

GameFeat_Cocos2D-X_Sample

cocos2d-xを使ったiOS/AndoridアプリにGAMEFEATの広告SDKを実装するサンプル
D
2
star
35

wp_hatebu_rss

はてなブックマークのRSSを投稿画面に入力する
PHP
1
star
36

iFixed

iPhoneでposition:fixedを簡易的に実現するJS
JavaScript
1
star
37

vercel-ai-sdk-demo

TypeScript
1
star
38

socket.io-chat-room-demo

socket.ioを使って複数のチャットルームを行き来するデモ
HTML
1
star
39

crawl-sample

Ruby
1
star
40

penpenpen

PENPENPEN can be written like a pen tablet
TypeScript
1
star
41

sample-ruby-for-ios

Objective-C
1
star
42

TiOriginalTab

TitaniumMobileで、オリジナルデザインのタブを作る
Objective-C
1
star
43

flood-fill-sample

HTML
1
star
44

vuejs-component-sample

JavaScript
1
star
45

active_archiver

Provide export / import to ActiveRecord, and support CarrierWave.
Ruby
1
star
46

actionmailer-sandbox

In a develop environment , you are forced to change the destination of the ActionMailer.
Ruby
1
star
47

zaru.github.com

zaru.github.com
Ruby
1
star
48

GAMEFEAT_cocos2dx_sample

GAMEFEAT cocos2dx sample project
C++
1
star
49

tech.basicinc.jp

エンジニアブログ
CSS
1
star
50

firebase-vuejs-sample-note

JavaScript
1
star
51

GameFeat_UnitySample

GameFeat SDK(Android)をUnityで使うサンプル
C#
1
star
52

cloudrun-rails-demo

Ruby on Rails on Cloud Run (GCP) demo
Dockerfile
1
star
53

happyhour

PHP
1
star
54

GameFeat_iOS_UnitySample

Objective-C
1
star
55

EC2HOST

With an IP address of EC2, to rewrite the local hosts file automatically.
PHP
1
star
56

slatic

Convert slack messages to static files, JSON and more
Go
1
star
57

Cocos2DX_AdStir

Cocos2DXを使ったiOS/AndroidアプリにAdStirを表示するサンプル
D
1
star