webpush
Sending notifications to browsers from a server, with VAPID keys and the standard encryption.
import webpush
A web push notification is a message a server sends to a user's browser even when the site is not open: a new chat message, a shipped order, a breaking news alert. This package is the server side. It makes the VAPID keys that identify your server, encrypts each message for one browser under RFC 8291 (aes128gcm) so the push service in between never sees its contents, signs the request, and posts it with net.http. The page side is plain JavaScript: a service worker and pushManager.subscribe.
The flow:
- Make a key pair once with
GenerateKeysand keep it; load it later withKeysFrom. - The page subscribes with the public key and sends you the subscription JSON; store it with the user as a
Subscription. - Send messages with
Send, and delete a subscription when the result saysgone.
Things that catch people out:
- New keys break every subscription. Each subscription is tied to the public key it was made with.
- A
ttlof 0 is replaced by the 28 day default, so "deliver now or drop it" cannot be expressed; use a short value such as 60 instead. - The payload size is not checked. More than 3993 bytes of text is still encrypted and sent, and the push service rejects it, usually with 413.
Sendwaits as long as the push service takes; it has no time limit, so sending to thousands of users one after another can be slow.KeysFromonly checks that both keys are non-empty.
Make the VAPID keys once
The VAPID key pair identifies your server to the push services, and every browser subscription is tied to its public key. If you make new keys at every start, all existing subscriptions stop working. So make them once, keep them somewhere safe, and load them with KeysFrom afterwards. The program keeps them in a file; a real server would more likely read them from its configuration or environment.
import webpush
import os
import str
func load_or_create(path: str): webpush.Keys:
if os.Exists(path):
lines := str.Split(os.ReadFile(path), "\n")
if lines.Len() >= 2:
ret webpush.KeysFrom(lines.Get(0), lines.Get(1))
end
end
fresh := webpush.GenerateKeys()
os.WriteFile(path, fresh.public_key + "\n" + fresh.private_key + "\n")
ret fresh
end
func main:
path := "vapid-keys.txt"
first := load_or_create(path)
second := load_or_create(path)
println "keys valid:", first.ok, second.ok
println "same keys on the second start:", first.public_key == second.public_key
println "public key length:", first.public_key.Len()
println "uncompressed point (starts with B):", str.StartsWith(first.public_key, "B")
os.Remove(path)
endThe public key is the 87 character text that the page passes as applicationServerKey to pushManager.subscribe. The private key never leaves the server.
Read the subscription the browser sends
After the user allows notifications, pushManager.subscribe() in the page returns a subscription. Its toJSON() form has an endpoint and two keys, p256dh and auth. Send that JSON to your server, read it into a Subscription with encoding.json and store it with the user. Encrypt reports through its ok argument whether the keys are usable, which is a cheap way to reject a broken subscription before you store it.
import webpush
import encoding.json
import str
func from_browser(text: str): webpush.Subscription:
ret webpush.Subscription {
endpoint = json.Get(text, "endpoint"),
p256dh = json.GetPath(text, "keys.p256dh"),
auth = json.GetPath(text, "keys.auth")
}
end
func main:
posted := `{"endpoint":"https://fcm.googleapis.com/fcm/send/dQw4w9WgXcQ:APA91b","expirationTime":null,"keys":{"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4","auth":"BTBZMqHH6r4Tts7J_aSIgg"}}`
sub := from_browser(posted)
println "endpoint:", sub.endpoint
println "push service:", str.StartsWith(sub.endpoint, "https://fcm.googleapis.com/")
println "p256dh length:", sub.p256dh.Len(), "auth length:", sub.auth.Len()
mut ok := false
body := webpush.Encrypt(sub, "{\"title\":\"Welcome\"}", ok)
println "keys usable:", ok, "encrypted body ready:", body.Len() > 0
broken := from_browser(`{"endpoint":"https://push.example.net/1","keys":{"p256dh":"abc","auth":"xyz"}}`)
_ := webpush.Encrypt(broken, "hi", ok)
println "broken keys usable:", ok
endKeep the payload small
A push message carries at most 4096 bytes after encryption, which leaves 3993 bytes for your text. Most services also deliver small messages faster. Send a title, a short body and a link, and let the page fetch anything bigger when the user opens the notification. The program shows how the size grows: the encrypted body adds a fixed header and the padding, and base64url makes it a third longer again.
import webpush
import encoding.json
func payload(title: str, text: str, url: str): str:
mut members := Vector {} as Vector<str>
members.Push(json.Member("title", title))
members.Push(json.Member("body", text))
members.Push(json.Member("url", url))
ret json.Object(members)
end
func main:
sub := webpush.Subscription {
endpoint = "https://push.example.net/x",
p256dh = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",
auth = "BTBZMqHH6r4Tts7J_aSIgg"
}
small := payload("New reply", "Sara answered your question", "/q/1042")
println small
mut ok := false
each n in [small.Len(), 1000, 3000, 3993]:
mut text := ""
until text.Len() < n:
text += "x"
end
sealed := webpush.Encrypt(sub, text, ok)
println "plain", n, "bytes, sealed and base64url encoded", sealed.Len()
end
endSend to many users and clean up
To notify everyone, loop over the stored subscriptions and call Send for each one. Look at the Result: ok means the push service accepted the message, gone (HTTP 404 or 410) means the user unsubscribed or the browser dropped the subscription, so delete it; anything else is worth trying again later. ttl says how long the service may hold the message for an offline device, urgency lets a phone save battery on low priority messages, and a message with the same topic replaces an older one that is still waiting.
import webpush
func main:
keys := webpush.KeysFrom("BLmOwafYGSjiuCX_1RSCO_n0YmacxYMDqitMydKE4A1Wp2qmUuMXg2IM_hzcrmZLun4jEu_lKfVdtnAp0LMK4NE", "Nhh4m4Va4yhL-53i302044iqeAeMtnOEYlIT2KWRJmg")
if not keys.ok:
println "the VAPID keys are broken"
ret 1
end
mut subs := Vector {} as Vector<webpush.Subscription>
subs.Push(webpush.Subscription { endpoint = "https://fcm.googleapis.com/fcm/send/abc", p256dh = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4", auth = "BTBZMqHH6r4Tts7J_aSIgg" })
subs.Push(webpush.Subscription { endpoint = "https://updates.push.services.mozilla.com/wpush/v2/def", p256dh = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4", auth = "BTBZMqHH6r4Tts7J_aSIgg" })
mut o := webpush.NewOptions("mailto:ops@example.com")
o.ttl = 3600
o.urgency = "high"
o.topic = "deploy"
mut keep := Vector {} as Vector<webpush.Subscription>
mut sent := 0
each s in subs:
r := webpush.Send(keys, s, `{"title":"Deploy finished","body":"Version 2.4 is live"}`, o)
if r.ok:
sent++
keep.Push(s)
else r.gone:
println "dropping", s.endpoint
else:
println "will retry", s.endpoint, r.status, r.error
keep.Push(s)
end
end
println "sent", sent, "of", subs.Len(), "and keeping", keep.Len()
ret 0
endThis program needs real subscriptions from a browser and network access, so it is only checked here. To try it, replace the sample endpoints with subscriptions taken from your own page.
Types
Keys
struct Keys| Name | Type | Description |
|---|---|---|
public_key | str = "" | The public key as url safe base64; this is what you give to applicationServerKey in the page JavaScript. |
private_key | str = "" | The private key; keep it secret. |
ok | bool = false | The keys are valid. |
import webpush
import str
func main:
fresh := webpush.GenerateKeys()
println fresh.ok, fresh.public_key.Len(), fresh.private_key.Len()
k := webpush.KeysFrom("BLmOwafYGSjiuCX_1RSCO_n0YmacxYMDqitMydKE4A1Wp2qmUuMXg2IM_hzcrmZLun4jEu_lKfVdtnAp0LMK4NE", "Nhh4m4Va4yhL-53i302044iqeAeMtnOEYlIT2KWRJmg")
println k.ok, webpush.KeysFrom("", "").ok
at := webpush.VapidHeaderAt(k, "https://fcm.googleapis.com", "mailto:ali@example.com", 1700000000)
println at
now := webpush.VapidHeader(k, "https://fcm.googleapis.com", "mailto:ali@example.com")
println str.StartsWith(now, "vapid t="), str.Contains(now, ", k=" + k.public_key)
mut o := webpush.NewOptions("mailto:ali@example.com")
println o.subject, o.ttl == webpush.DEFAULT_TTL, o.ttl / 86400
o.urgency = "high"
o.topic = "news"
o.ttl = 3600
println o.urgency, o.topic, o.ttl
endSubscription
struct SubscriptionpushManager.subscribe and sends to your server.| Name | Type | Description |
|---|---|---|
endpoint | str = "" | The address of the browser push service. |
p256dh | str = "" | The public key of the browser, from the keys part of the subscription. |
auth | str = "" | The authentication secret, from the same part. |
import webpush
func main:
sub := webpush.Subscription {
endpoint = "https://push.example.net/x",
p256dh = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",
auth = "BTBZMqHH6r4Tts7J_aSIgg"
}
mut good := false
body := webpush.EncryptWith(sub, "When I grow up, I want to be a watermelon", "yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw", "DGv6ra1nlYgDCS1FRnbzlw", good)
println good
println body
one := webpush.Encrypt(sub, "hello", good)
two := webpush.Encrypt(sub, "hello", good)
println good, one != two, one.Len() == two.Len()
endOptions
struct Options| Name | Type | Description |
|---|---|---|
subject | str = "" | Your contact address, as a mailto: or a web address; the services require it. |
ttl | int = 2419200 | How many seconds the service should hold the message for a browser that is off. 0 or less sends the 28 day default. |
urgency | str = "" | The urgency: very-low, low, normal or high; empty sends no header, which services treat as normal. The value is not checked. |
topic | str = "" | The topic; a new message with the same topic replaces an earlier undelivered one. |
The example for this item is shown with the ones above: webpush-Keys.salam
Result
struct Result| Name | Type | Description |
|---|---|---|
ok | bool = false | The service accepted the message. |
status | int = 0 | The HTTP status code of the service. |
gone | bool = false | The subscription is no longer valid (404 or 410); delete it from your database. |
error | str = "" | Why the send failed: a network error, or the body of the service's answer when it is short. |
import webpush
func main:
k := webpush.KeysFrom("BLmOwafYGSjiuCX_1RSCO_n0YmacxYMDqitMydKE4A1Wp2qmUuMXg2IM_hzcrmZLun4jEu_lKfVdtnAp0LMK4NE", "Nhh4m4Va4yhL-53i302044iqeAeMtnOEYlIT2KWRJmg")
sub := webpush.Subscription {
endpoint = "https://fcm.googleapis.com/fcm/send/abc",
p256dh = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",
auth = "BTBZMqHH6r4Tts7J_aSIgg"
}
o := webpush.NewOptions("mailto:ali@example.com")
r := webpush.Send(k, sub, `{"title":"hello","body":"you have a new message"}`, o)
if r.ok:
println "sent", r.status
else r.gone:
println "the subscription has expired; delete it"
else:
println "error:", r.status, r.error
end
endConstants and variables
DEFAULT_TTL
const DEFAULT_TTL: i32 = 2419200The example for this item is shown with the ones above: webpush-Keys.salam
Functions
GenerateKeys
func GenerateKeys(): KeysThe example for this item is shown with the ones above: webpush-Keys.salam
VapidHeaderAt
func VapidHeaderAt(keys: Keys, audience: str, subject: str, epoch_seconds: i64): strAuthorization header for the service at the given address, at the given time in Unix seconds. The signature is deterministic, so the same input gives the same output.The example for this item is shown with the ones above: webpush-Keys.salam
VapidHeader
func VapidHeader(keys: Keys, audience: str, subject: str): strThe example for this item is shown with the ones above: webpush-Keys.salam
EncryptWith
func EncryptWith(sub: Subscription, payload: str, as_private: str, salt: str, ok &: bool): strEncrypt.The example for this item is shown with the ones above: webpush-Encrypt.salam
Encrypt
func Encrypt(sub: Subscription, payload: str, ok &: bool): strThe example for this item is shown with the ones above: webpush-Encrypt.salam
Send
func Send(keys: Keys, sub: Subscription, payload: str, opts: Options): ResultThe example for this item is shown with the ones above: webpush-Send.salam
NewOptions
func NewOptions(subject: str): OptionsThe example for this item is shown with the ones above: webpush-Keys.salam
KeysFrom
func KeysFrom(public_key: str, private_key: str): Keysok is false when either one is empty. The keys themselves are not checked until the first Send.The example for this item is shown with the ones above: webpush-Keys.salam