Skip to content

Commit

Permalink
Update README for subscribing
Browse files Browse the repository at this point in the history
This change updates a long-standing piece of Push Subscription
directions in the README which demonstrates setting of the
applicationServerKey into a Uint8Array from the decoded raw bytes of the
vapid public key.

This step is cumbersome and there is a simpler alternative.

The Push API docs for the PushSubscriptionOptions interface say of the
applicationServerKey:

> When provided as a DOMString, the value MUST be encoded using the
base64url encoding [RFC7515].
https://www.w3.org/TR/push-api/#dom-pushsubscriptionoptions-applicationserverkey

RFC 7515 states that the Base64 url-safe encoding omit the padding
characters:

> Base64 encoding using the URL- and filename-safe character set defined
in Section 5 of RFC 4648 [RFC4648], with all trailing '=' characters
omitted https://www.rfc-editor.org/rfc/rfc7515

It turns out the generated vapid public is already Base64 url-safe
encoded! However, for historical reasons, Ruby's Base64.urlsafe_encode64
method includes the padding character, "=", incorrectly by default. This
behavior exists in the library's current vapid key generation.
Therefore, the directions include explicit deletion of the "=" character.

For historical discussion of Ruby's encoding issue, see:
https://bugs.ruby-lang.org/issues/10740
  • Loading branch information
rossta committed Jan 30, 2024
1 parent f140f28 commit 0f254c4
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,23 @@ navigator.serviceWorker.register('/service-worker.js')

### Subscribing to push notifications

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.
The encoded VAPID public key you generated earlier needs to be made available to JavaScript, which can be done when rendering the HTML template in Ruby:

```javascript
window.vapidPublicKey = new Uint8Array(<%= Base64.urlsafe_decode64(ENV['VAPID_PUBLIC_KEY']).bytes %>);
```html
<script type="application/javascript">
window.vapidPublicKey = <%= ENV['VAPID_PUBLIC_KEY'].delete('=') %>);
</script>
```

*Alternative* The VAPID public key may also made available to the client as a `UInt8Array` from the urlsafe-decoded bytes.

```html
<script type="application/javascript">
window.vapidPublicKey = new Uint8Array(<%= Base64.urlsafe_deco
de64(ENV['VAPID_PUBLIC_KEY']).bytes %>);
</script>
```

Your JavaScript code uses the `pushManager` interface to subscribe to push notifications, passing the VAPID public key to the subscription settings.

```javascript
Expand Down

0 comments on commit 0f254c4

Please sign in to comment.