Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · packages/push

Notifications that arrive with every tab closed

Web Push lets a server notify a browser that agreed to it, even with none of the site's tabs open. This plugin has every part: a button that asks and subscribes, a table of each browser's subscription, and a job that sends.

Use it for news a user wants while away from your site: a reply to their question, a finished export, a shipped order.

A first app#

Each file below is from packages/push/example: a page with the subscribe button and a button that notifies everyone. It can't run on this site, which is static files: Web Push needs a server.

1. Keys. Web Push identifies your server by a key pair, the VAPID keys. Under rocx dev you need none to start: the server makes a pair for the run and logs the two settings that keep it:

The server's log
WARN  push: no VAPID keys, so this run made a pair, which the next start replaces (a browser subscribed with it then subscribes again); to keep it, put these in .env, a line each: VAPID_PUBLIC_KEY=BKx… VAPID_PRIVATE_KEY=3q…

rocx dev restarts the server at each change to its code, and a new pair means each browser's button shows off until clicked again. To keep the pair, copy the two settings into .env, which rocx dev reads as it starts. Without VAPID_SUBJECT, the run tells push services mailto:dev@example.com, and logs that.

A deployed server needs all three in its environment: VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY and VAPID_SUBJECT (mailto: and an address, or an https: URL). Give it its own pair: under rocx dev, /__rocx/push/keys answers a new one each time, as the two lines to set.

curl -s localhost:8080/__rocx/push/keys
VAPID_PUBLIC_KEY=BNc…
VAPID_PRIVATE_KEY=Hw…

A browser can only be sent to with the pair it subscribed with, so keep the keys once you have users. Without --dev, a missing key or subject, or two keys that aren't a pair, stop the server at start, and it says why and how to make a pair.

2. The plugin. Name the package in the app's header and list its plugin, with the jobs plugin, which runs the job that sends:

packages/push/example/main.roc
## An app's side of push, as small as it gets: a page with `<PushButton>` and a button that notifies
## every browser (`routes/push/announce`), and the routes the button asks (routes/push/key/,
## subscribe/, unsubscribe/: the package's handlers, D-116). The push plugin brings the rest (D-051):
## the table, the job that delivers, the service worker at the site's root and the page's script.
## The jobs plugin (packages/jobs) runs its job. It names no database, so the table is in SQLite's
## `data/app.db` (D-105).
app [program] { jobs: "../../jobs/main.roc", pf: platform "../../../server/platform/main.roc", push: "../main.roc" }

import jobs.Job
import push.Push
import Generated/App

program = App.program({
	init!: |_started| Ok({}),
	plugins: [Job.plugin({ jobs: App.jobs }), Push.plugin({})],
})

The plugin brings:

Its three endpoints are your routes, each a file calling the package's handler behind its folder's middleware: GET /push/key (the public key), POST /push/subscribe and POST /push/unsubscribe, where <PushButton api="/push"> looks. Put them elsewhere and give the button that path.

routes/push/subscribe/+server.roc
import push.Push

# Whose the subscription is: "" for a visitor, or the app's id for the user this folder's middleware
# handed on (`context.member`); then Push.notify! can send to that user's browsers.
respond! = |{ request, .. }| Push.subscribe_route!(request, "")

Push.key_route!(request) and Push.unsubscribe_route!(request, owner) answer the other two the same way.

3. The page. The button, and a handler that asks an endpoint to notify everyone:

packages/push/example/routes/+page.rocx
import pf.Html
import pf.Server
import pf.Solid exposing [create_signal!]
import push.PushButton
import ../Generated/Api

## Asks the server to notify everyone (`POST /push/announce`), from the button's handler: how
## many it queued, or why not.
announce! : {} => Str
announce! = |{}|
	match Api.post_push_announce({}).send!({}) {
		Ok(said) => said
		Err(problem) => Server.explain(problem)
	}

view! = |_| {
	(said!, set_said!) = create_signal!("")
	<main>
		<h1>Push</h1>
		<PushButton api="/push" />
		<button type="button" on:click={|| set_said!(announce!({}))}>Notify everyone</button>
		<p>{said!()}</p>
	</main>
}
packages/push/example/routes/push/announce/+server.roc
import pf.Server
import pf.Endpoint
import push.Notification
import push.Options
import push.Push

## POST /push/announce: queues a notification for every browser that subscribed. How many; a
## database that failed is a plain 500, its why on the server's log (`Failed`).
post! : { request : Server.Request, params : {}, context : c, body : {} } => Try(Str, Endpoint.Refusal)
post! = |_|
	match Push.broadcast!({ ..Notification.new("Hello", "A notification from the example"), url: "/" }, Options.defaults) {
		Ok(count) => Ok("Queued: ${count.to_str()}")
		Err(why) => Err(Failed(why))
	}

<PushButton>#

A button that turns this browser's notifications on and off. A click calls the plugin's script (static/push.js) with Browser.call!, which asks the browser's permission, registers the service worker, subscribes with the server's public key and posts the subscription to the server. Turning off unsubscribes and tells the server. Browsers show the permission prompt only during a click, key press or tap, so subscribing starts from a button.

PropIs
api : Str where your routes for push are: with "/push", GET /push/key, POST /push/subscribe and POST /push/unsubscribe

Browser.call! can't return an answer, so the script reports with a pushstate event, which every <PushButton> on the page hears: how a click went, and, when the page loads, where this browser stands. The button shows each report as a PushState:

The script saysThe button shows
"": until the script has looked Turn notifications on
off: the browser can, and hasn't subscribed Turn notifications on
working: after a click: asking, subscribing, telling the server One moment…, disabled
on: subscribed, and the server has it Turn notifications off. Beside it: Notifications are on in this browser.
blocked: the user said no to the prompt Turn notifications on, disabled. Beside it: Notifications are blocked for this site: the browser's site settings can allow them.
unsupported: no service worker or Push API here, or not a secure page Turn notifications on, disabled. Beside it: This browser can't show notifications from a site. On an iPhone or iPad, add the site to the Home Screen, and open it from there.
failed:no network: a click went wrong: failed:, then why Turn notifications on. Beside it: That didn't work: no network

aria-pressed says whether notifications are on, and a screen reader reads the note when it changes (aria-live). On an iPhone or iPad, a site gets Web Push only once it is added to the Home Screen and opened from there.

The button: packages/push/components/PushButton.rocx
packages/push/components/PushButton.rocx
import pf.Html
import pf.Browser
import pf.Solid exposing [create_memo!, create_signal!]
import push.PushState

## A button that turns this browser's notifications on, and off again. Its click asks the
## browser's permission (a browser asks only on a click, a key or a tap, so the prompt comes from
## this one), subscribes at the browser's push service with the server's VAPID key, and posts the
## subscription to the app; turning them off unsubscribes, and tells the app. The push plugin's
## script, `static/push.js`, does the browser's part (`Browser.call!("push.subscribe", { api: api })`) and says
## how it went with a `pushstate` event, which every `<PushButton>` on the page hears
## (`PushState`).
##
## `api` is where the app's routes for push are (D-116: `Push.key_route!` and the rest, in route
## files of its own): with `"/push"`, `GET /push/key` (the public key), `POST /push/subscribe` and
## `POST /push/unsubscribe`.
PushButton := [].{
	view! : { api : Str } => Html
	view! = |{ api }| {
		(said!, set_said!) = create_signal!("")
		state! = create_memo!(|| PushState.parse(said!()))
		<span class="push-button" data-push-state on:pushstate.value={set_said!}>
			<button
				type="button"
				disabled?={state!().is_stuck()}
				aria-pressed={if (state!().is_on()) "true" else "false"}
				on:click={|| Browser.call!(if (state!().is_on()) "push.unsubscribe" else "push.subscribe", { api: api })}
			>
				{state!().label()}
			</button>
			<small aria-live="polite">{state!().note()}</small>
		</span>
	}

	<style>
		.push-button {
			display: inline-flex;
			flex-direction: column;
			gap: 0.25rem;
		}
		small:empty {
			display: none;
		}
	</style>
}

A notification#

A notification is a title, a body, the page a click opens (url) and a tag. Its options tell the push service how to treat the message. Change them below to see what a server would send, worked out by the package's own functions in your browser.

Kept for
Urgency

The data, Notification.to_json: 78 of 3993 bytes

{"title":"Your export is ready","body":"orders.csv, 3 MB","url":"/exports/17"}

The headers the push service reads, Options.headers

TTL: 86400
Urgency: normal

Push.notify! would queue it: a job for each of the user's browsers.

The request has two more headers: Authorization (the VAPID token, vapid t=…, k=…) and Content-Encoding: aes128gcm. The data is encrypted: the push service sees only bytes.

FieldIs
title : Strthe notification's first line; empty: the site's host name
body : Strthe text under it
url : Strthe page a click opens, on this site only; empty: the front page
tag : Stra newer notification with the same tag replaces this one, rather than piling up
icon : Stran image's URL

Notification.new(title, body) makes one with the other fields empty, and { ..Notification.new(title, body), url: "/orders/17" } sets more. Empty fields are left out of the JSON.

OptionIs
ttl : U64 how many seconds the push service keeps the message for a browser that is offline. 0 means now or never; more than four weeks is sent as four weeks.
urgency : [VeryLow, Low, Normal, High] how soon it must arrive. A phone on battery may hold the low ones back.
topic : Str a newer message with the same topic replaces one still waiting, so only the latest status arrives. At most 32 characters, of letters, digits, - and _.

Options.defaults is a day, Normal, and no topic.

This demo: site/Demos/PushCompose.rocx
site/Demos/PushCompose.rocx
import pf.Html
import pf.Solid exposing [create_memo!, create_signal!]
import push.Notification
import push.Options
import push.WebPush

## A notification, and how a push service should treat it: what a server sends. The push page's
## live demo, run by the package's own functions in the browser: `Notification.to_json` (the data
## the service worker reads), `Options.headers` (what the push service reads), and the two checks
## `Push.notify!` makes before it queues anything (`Options.check`, and `WebPush.max_data`).
PushCompose := [].{

	## How long a push service keeps the message for a browser that is offline.
	ttls : List({ label : Str, seconds : U64 })
	ttls = [
		{ label: "Now or never", seconds: 0 },
		{ label: "An hour", seconds: 3_600 },
		{ label: "A day", seconds: 86_400 },
		{ label: "Four weeks", seconds: 2_419_200 },
	]

	## How soon it must arrive: a phone on battery may hold the low ones back.
	urgencies : List({ label : Str, urgency : [VeryLow, Low, Normal, High] })
	urgencies = [
		{ label: "Very low", urgency: VeryLow },
		{ label: "Low", urgency: Low },
		{ label: "Normal", urgency: Normal },
		{ label: "High", urgency: High },
	]

	view! : {} => Html
	view! = |{}| {
		(title!, set_title!) = create_signal!("Your export is ready")
		(body!, set_body!) = create_signal!("orders.csv, 3 MB")
		(url!, set_url!) = create_signal!("/exports/17")
		(tag!, set_tag!) = create_signal!("")
		(ttl!, set_ttl!) = create_signal!(Options.defaults.ttl)
		(urgency!, set_urgency!) = create_signal!(Options.defaults.urgency)
		(topic!, set_topic!) = create_signal!("")
		json! = create_memo!(|| { ..Notification.new(title!(), body!()), url: url!(), tag: tag!() }.to_json())
		options! = create_memo!(|| { ttl: ttl!(), urgency: urgency!(), topic: topic!() })
		size! = create_memo!(|| json!().to_utf8().len())
		verdict! = create_memo!(|| verdict(options!(), size!()))
		<div class="compose">
			<div class="compose-fields">
				<label>Title <input type="text" value={title!()} on:input.value={set_title!} /></label>
				<label>Body <input type="text" value={body!()} on:input.value={set_body!} /></label>
				<label>URL <input type="text" value={url!()} on:input.value={set_url!} /></label>
				<label>Tag <input type="text" value={tag!()} on:input.value={set_tag!} /></label>
				<label>Topic <input type="text" value={topic!()} on:input.value={set_topic!} /></label>
			</div>
			<fieldset class="ttl">
				<legend>Kept for</legend>
				{...ttls.map(|each|
					<button type="button" aria-pressed={if (ttl!() == each.seconds) "true" else "false"} on:click={|| set_ttl!(each.seconds)}>
						{each.label}
					</button>
				)}
			</fieldset>
			<fieldset class="urgency">
				<legend>Urgency</legend>
				{...urgencies.map(|each|
					<button type="button" aria-pressed={if (urgency!() == each.urgency) "true" else "false"} on:click={|| set_urgency!(each.urgency)}>
						{each.label}
					</button>
				)}
			</fieldset>
			<p class="compose-caption">
				The data, <code>Notification.to_json</code>: <span class="size">{size!().to_str()}</span> of {WebPush.max_data.to_str()} bytes
			</p>
			<pre class="json"><code>{json!()}</code></pre>
			<p class="compose-caption">The headers the push service reads, <code>Options.headers</code></p>
			<pre class="headers"><code>{Str.join_with(options!().headers().map(|(name, value)| "${name}: ${value}"), "\n")}</code></pre>
			<p class="verdict" class:refused={verdict!().refused} aria-live="polite">{verdict!().said}</p>
		</div>
	}

	<style>
		.compose-fields {
			display: grid;
			gap: var(--space-2);
			margin-bottom: var(--space-4);
		}

		.compose-fields label {
			display: grid;
			grid-template-columns: 3.5rem 1fr;
			align-items: center;
			gap: var(--space-2);
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		fieldset {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			gap: var(--space-2);
			margin: 0 0 var(--space-3);
			padding: 0;
			border: 0;
		}

		legend {
			float: left;
			width: 5.5rem;
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		fieldset button {
			padding: var(--space-1) var(--space-3);
			border-radius: var(--pill);
			background: var(--accent-soft);
			color: var(--accent);
			font-size: var(--size-sm);
			font-weight: 500;
		}

		fieldset button[aria-pressed="true"],
		fieldset button[aria-pressed="true"]:hover:not(:disabled) {
			background: var(--accent);
			color: var(--accent-text);
		}

		.compose-caption {
			margin: var(--space-4) 0 var(--space-1);
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		pre {
			margin: 0;
			white-space: pre-wrap;
			overflow-wrap: anywhere;
		}

		.verdict {
			margin: var(--space-4) 0 0;
			padding: var(--space-2) var(--space-3);
			border-radius: var(--radius-sm);
			background: var(--good-soft);
			color: var(--good);
			font-size: var(--size-sm);
		}

		.verdict.refused {
			background: var(--bad-soft);
			color: var(--bad);
		}
	</style>
}

## What `Push.notify!` would do with them: queue it, or refuse it, and why.
verdict : Options, U64 -> { refused : Bool, said : Str }
verdict = |options, size|
	match Options.check(options) {
		Err(BadTopic) => { refused: Bool.True, said: "Push.notify! would refuse it: a topic is 32 characters at most, of letters, digits, - and _." }
		Ok(_) =>
			if size > WebPush.max_data {
				{ refused: Bool.True, said: "Push.notify! would refuse it: a push message holds ${WebPush.max_data.to_str()} bytes at most." }
			} else {
				{ refused: Bool.False, said: "Push.notify! would queue it: a job for each of the user's browsers." }
			}
	}

Sending#

On the server, a job or endpoint calls Push.notify! (one user's browsers) or Push.broadcast! (every browser). Each checks the notification and options, queues a push.deliver job for each subscription, and answers how many it queued. Inside a transaction, the jobs are queued only if it commits.

packages/push/Push.roc
## Queues `notification` for each of `owner`'s subscriptions: how many. In a transaction
## (`Db.transaction!`), they are queued only if it commits.
notify! : Str, Notification, Options => Try(U64, Str)
notify! = |owner, notification, options|
	match PushStore.of_owner!(owner) {
		Ok(ids) => queue_each!(ids, Notification.to_json(notification), options)
		Err(DbErr(why)) => Err(why)
		Err(BadRow(why)) => Err(why)
	}

## Queues `notification` for every subscription: how many.
broadcast! : Notification, Options => Try(U64, Str)
broadcast! = |notification, options|
	match PushStore.everyone!({}) {
		Ok(ids) => queue_each!(ids, Notification.to_json(notification), options)
		Err(DbErr(why)) => Err(why)
		Err(BadRow(why)) => Err(why)
	}

A jobs worker sends each message; the push service's answer decides what happens next:

The push service answersThe job
201, or any 2xxis done, and notes when it sent
404 or 410deletes the subscription: the browser unsubscribed, or it expired
408, 429 or 5xx, with Retry-Aftersends it again at that time, five times at most, while the message's TTL lasts
408, 429 or 5xx without it, or no answerfails the attempt; the worker tries again, waiting longer each time (five attempts)
400, 401, 403, 413, or anything elselogs it and notes it on the subscription; sending again wouldn't help

A retry sends the TTL that is left, so a message never outlives it. A 403 doesn't delete the subscription: push services answer 403 to wrong VAPID keys, and a mistake in the server's settings shouldn't delete every subscription.

How it works#

  1. A click on <PushButton> asks the browser's permission.
  2. The browser subscribes at its push service (Google's for Chrome, Mozilla's for Firefox, Apple's for Safari, Microsoft's for Edge) with the server's public key. It gets a subscription: a URL at that service, and two keys.
  3. The page posts the subscription to the app, which keeps a row for each browser.
  4. Later, the server calls Push.notify!, which queues a job for each of the user's subscriptions.
  5. The job encrypts the notification for that one browser (RFC 8291), signs a token that says which server sent it (VAPID, RFC 8292), and posts both to the subscription's URL (RFC 8030). The elliptic-curve work and the AES are the server platform's (P256 and AesGcm).
  6. The push service wakes the browser. The package's service worker shows the notification, and a click on it opens the page it names.

The modules#

Plain Roc, on no platform: the formats, the key derivation, the token, and what each answer means. The browser's half of an app can use them too (browser.roc lists them). roc test packages/push/main.roc checks them against the RFCs' own examples. Every function is in packages/push/README.md.

ModuleWhat it does
Subscriptiona browser's subscription: parse (the page's JSON), from_body (an endpoint's body), from_text and to_text (a table row), to_json; known_service: is it at Chrome's, Firefox's, Safari's or Edge's push service?
Notificationwhat the service worker shows: new, to_json, data
Optionshow a push service treats a message: defaults, check (the topic), headers, remaining (the TTL left for a retry)
Deliveryrequest (the POST to a subscription's URL); outcome (what an answer means: Delivered, Gone, RetryAfter(ms), Retry(why), Refused(why)), retry_after, http_date
Vapidthe server's token, RFC 8292: Keys and from_text (from the environment), audience, claims (valid 12 hours), signing_input, token, authorization
WebPushthe message's encryption, RFC 8291: prepare (everything before the AES), body, max_data (3993 bytes)
Ecethe aes128gcm content coding, RFC 8188: header, parse_header, pad, unpad, keys, nonce
PushStatewhere a browser stands, as the page's script reports it: what <PushButton> shows

HMAC-SHA-256, HKDF-SHA-256 and base64url come from the crypto package, which push names in its own header: an app names push alone.

The plugin, Push.plugin({}), on the server platform, which the package names in its header (plugins): its table and its migrations (migrations/, for Postgres and for SQLite), the job that sends, and the handlers the app's routes call. Each function's owner is the app's id for a user, as text, or "" for a visitor.

ModuleWhat it does
Pushplugin({}), the plugin, with no options; key_route!, subscribe_route! and unsubscribe_route!, the handlers the app's route files call; subscribe!(body, owner) and unsubscribe!(endpoint, owner), which those call; notify! and broadcast!; public_key! and keys! (from the environment, or under --dev without keys the pair the run made); deliver, the job; send!, one attempt
PushStorethe push_subscriptions table: save! (a row for each endpoint), remove!, remove_id!, find!, of_owner!, everyone!, and delivered! and refused!, which the job calls

The browser's part: <PushButton>, in components/, which rocx build copies into the app, and these files in static/, which the plugin serves:

FileWhat it does
push.jsthe page's script, at /rocx/plugins/push/push.js, on every page: the push.subscribe and push.unsubscribe effects the button calls. Once a visit, it sends the server the browser's subscription again, in case it lost it. On a site served under a base path (/rocx/), every URL it uses is under that path.
push-sw.jsthe service worker, at the site's root (/push-sw.js), so its scope is the whole site. It shows a message's notification; a click focuses a tab already at its URL, or opens one. When the push service replaces a subscription, it tells the server.

Safety#

Status#

Tested today:

No test sends to a real push service (Google's, Mozilla's, Apple's or Microsoft's). They accept what the RFCs say, which the tests check; a real browser's first notification is the last check.

Not yet (each has a proposal in packages/push/PROPOSALS.md):

A limit: a message holds 3993 bytes of data, the notification's JSON. Push.notify! refuses a longer one.