Osy#betaRun it on Osyrin: osyrin.com

Reference / UI

Notification channels and Web Push — a person told at once, on their phone

app.Notifications = new NotificationsSetup { Channels = [ new WebPushChannel { PublicKey = "…", PrivateKey = Secret.VapidKey, Subject = "mailto:…" } ] }; · use Osysharp.Notifications@1 { egress "fcm.googleapis.com"; … } · PushPublicKey() · SubscribeToPush(endpoint, p256dh, auth) · UnsubscribeFromPush(endpoint) · UnreadNotificationLines(take) · class MyChannel : INotificationChannel { … }

Beside the bell and mail, `Osysharp.Notifications` tells a person AT ONCE on the app's channels — each an `INotificationChannel` named in `NotificationsSetup.Channels`. The kit's own is Web Push: every browser a person allowed (a phone's too) is pushed to the moment a notification reaches their bell, if their own setting says so — everything, mentions only, or nothing. A push is signed with the app's VAPID key and carries nothing: the browser asks the app for the person's unread lines, signed in as them. Each send is its own row, tried again while a push service is down, and every try asks again whether the person may read what it is about.

preview1 example compiled by CIuikitnotificationspush

Summary#

Name the app's VAPID key pair and grant the push services its people's browsers use — then every notification that reaches a person's bell is pushed to each browser they allowed:

use Osysharp.Notifications@1 { egress "fcm.googleapis.com"; egress "updates.push.services.mozilla.com";
                               egress "*.push.apple.com"; egress "*.notify.windows.com"; }

app.Secrets = [ new Secret("VapidKey") ];
app.Notifications = new NotificationsSetup { AppName = "Harbour", Channels = [
  new WebPushChannel { PublicKey = "BKyBWg3t…", PrivateKey = Secret.VapidKey, Subject = "mailto:[email protected]" } ] };

What is pushed is each person's own choice, on their notification settings page.

Signature#

// Osysharp.Notifications 1.3.0
class NotificationsSetup {
  List<INotificationChannel> Channels = [];          // none by default: the bell and mail only
  int ChannelAttempts = 5;                            // tries before a send is given up on
  TimeSpan ChannelRetryAfter = TimeSpan.FromMinutes(1);   // doubling after each refusal, never past an hour
}

interface INotificationChannel {
  string Key { get; }                                  // "push" — written on every send, never renamed
  bool IsReady();                                      // its keys set; one that is not sends nothing
  void Send(Principal person, Notification n, string idempotencyKey);   // throw to be tried again
  bool Wants(Principal person, Notification n) => true;                 // the person's own settings
  bool Reaches(Principal person) => true;                               // somewhere to send to
}

class WebPushChannel : INotificationChannel {          // Key "push"
  string PublicKey;          // VAPID public key: the uncompressed P-256 point, base64url (what browsers subscribe with)
  string PrivateKey;         // VAPID private key, PEM — from a secret
  string Subject;            // "mailto:…" or "https://…" — who a push service may contact about the app
  TimeSpan TimeToLive = TimeSpan.FromHours(12);
}

// what the browser calls, signed in as its person — publish them in the app's API
string PushPublicKey()                                             // "" when the app pushes nothing
void SubscribeToPush(string endpoint, string p256dh = "", string auth = "")
void UnsubscribeFromPush(string endpoint)
List<NotificationLine> UnreadNotificationLines(int take = 5)      // what a woken service worker shows

enum NotificationPush { Everything, Mentions, Off }               // NotificationPreferences.Push — "Push to my devices"
entity PushSubscription { Person, EndpointHash, SealedEndpoint, SealedKeys, Host, At, LastPushedAt, Problem }
entity NotificationSend { Notification, Recipient, Channel, Attempts, SentAt, Problem, State }
enum NotificationSendState { Queued, Retrying, Sent, NotSent, Failed }

Description#

When a channel is told#

A notification reaches a person's bell after the commit that wrote it ([[ui-notifications-kit#notify]]). In the same step, for each channel that is ready and Reaches the person, the kit writes a NotificationSend; a workflow sends it after that commit. A second notification that joins an unread one ([[ui-notifications-kit#dedup]]) is sent again — something happened again — about the one in the bell. A notification that is withheld or merged before it reached the bell writes none.

Each try, in this order — the first that fails ends the send as Not sent, with why:

  1. the channel is still named and ready;
  2. the notification is still in the bell and unread;
  3. the recipient's account is on;
  4. the recipient may read what it is about — Records.MayRead, of the record as stored, under their own rules. Asked at every try, because a send can wait an hour for a push service and access lost meanwhile must end it. SECURITY-INVARIANT notifications-only-about-what-the-recipient-may-read;
  5. their own settings want it (Wants), and the channel still reaches them (Reaches).

Then Send. A throw is a refusal: tried again after ChannelRetryAfter, doubling, up to ChannelAttempts, then Failed. A send's recipient can read their own sends; nobody writes them but the kit.

What a push carries — nothing#

The kit's Web Push posts an EMPTY body to the browser's push service: no sentence, no title, no record. The browser's service worker, woken, asks the app for UnreadNotificationLines() — as its person, whose sign-in it carries — and shows those. So what appears is read under the person's own rules at the moment it appears, in their language, and nothing about a record passes through Google's, Mozilla's or Apple's servers. A channel written as an adapter that DOES carry words must say them as its recipient would read them; it is handed the notification, not its words.

The request a push service receives#

Method, addressPOST the subscription's endpoint
Bodyempty (Content-Length: 0) — no Content-Encoding
Authorizationvapid t=<JWT>, k=<PublicKey> (RFC 8292)
the JWTheader {"typ":"JWT","alg":"ES256"}; claims aud = the endpoint's origin (https://fcm.googleapis.com), exp = now + 12 h, sub = Subject; signed ES256 with PrivateKey
TTLTimeToLive in seconds — 43200 by default
Urgencyhigh for a mention, else normal
Topicthe first 32 hex characters of SHA-256 of the notification's key — a push still waiting at the service is replaced by the next about the same thing

A 2xx is sent. 404 or 410 — the browser unsubscribed, or the service expired it — drops that subscription and is not a refusal. Anything else, or no answer, is a refusal: the send is tried again, to all of the person's browsers. A repeat is harmless — the service worker shows the same unread lines, under the same tag.

The page asks for the key and subscribes the browser#

The page asks PushPublicKey() — "" means the app pushes nothing, so it offers no switch — and, when the person turns notifications on, subscribes and hands the subscription over:

const reg = await navigator.serviceWorker.register("/push-worker.js");
const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: publicKey });
const { endpoint, keys } = sub.toJSON();          // → SubscribeToPush(endpoint, keys.p256dh, keys.auth)

The service worker, on push, fetches UnreadNotificationLines() (same origin, so the person's sign-in goes with it) and shows the newest — title the line's Sentence, body its Title, tag its Id, data.url its Link — and on notificationclick opens data.url. On sign-out, the page calls UnsubscribeFromPush(endpoint).

The kit serves no script and opens no route: the app publishes PushPublicKey, SubscribeToPush, UnsubscribeFromPush and UnreadNotificationLines in its API and serves its own service worker.

A person's own subscriptions#

SubscribeToPush keeps one PushSubscription per person and browser — the same browser again is the same row. The endpoint is a credential (whoever holds it can wake that browser), so it is sealed with the app's own key (Crypto.Encrypt) and found by its SHA-256; the browser's p256dh and auth keys are sealed beside it. A person adds and removes only their own, and nobody reads the endpoint or keys back — their owner included. SECURITY-INVARIANT push-subscriptions-are-their-persons-own. A transport error that quotes the endpoint is recorded by its host only.

What is pushed is theirs to choose#

The notification settings page gains Push to my devices — Everything, as it happens (the default: allowing a browser was the asking), Only when somebody mentions me, or Nothing. Mail is its own choice beside it: a person who turned push off still gets the mail their mail setting says.

The kit declares its egress and the app grants it#

The kit declares egress consumer; — a push service is the BROWSER's, chosen at run time — and the app grants the ones its people's browsers use ([[project-package#egress-any]]): Chrome and Edge fcm.googleapis.com, Firefox updates.push.services.mozilla.com, Safari *.push.apple.com, legacy Edge *.notify.windows.com. An app that grants none and names no channel reaches nothing. One key pair serves every push service; make it once:

openssl ecparam -genkey -name prime256v1 -noout | openssl pkcs8 -topk8 -nocrypt > vapid.pem   # → osy secret set VapidKey
openssl pkey -in vapid.pem -pubout -outform DER | tail -c 65 | base64 | tr '/+' '_-' | tr -d '='   # → PublicKey

Examples#

A studio that pushes to its writers#

app Studio {
  use Osysharp.Identity@0;
  use Osysharp.Notifications@1 { egress "fcm.googleapis.com"; egress "*.push.apple.com"; }
  use Osysharp.Mail@0;
  use Osysharp.EmailTemplates@0;
  use Osysharp.Workflow;
  use Osysharp.Http;
  use Osysharp.Ui;
  model "model/**/*.osy";
}

using Osysharp.Identity;
using Osysharp.Notifications;

[Role] enum StudioRole { Authenticator, Writer }
policy IsWriter => RoleGrant.Any(g => g.Member == user && g.Role == StudioRole.Writer);
policy ReceivesNotifications => IsWriter;
policy ManagesClock => IsWriter;   // who sets the time zone the digest's morning is in

[Title(Title)]
entity Draft {
  [Required, MaxLength(120)] string Title;
  security { allow read, create, update when IsWriter; }
}

app.Secrets = [ new Secret("VapidKey") ];
app.Notifications = new NotificationsSetup { AppName = "Studio", Channels = [
  new WebPushChannel { PublicKey = "BKyBWg3tPRza-Ac5CpO2ekz-ZdHuOfq_4Bjv4yGKZj89DhsRLinWzDX7jfLQ5G7i8apwz9xndj6mSHYmaz3ec04",
                       PrivateKey = Secret.VapidKey, Subject = "mailto:[email protected]" } ] };

/// The page's "Notify me on this device" switch hands the browser's subscription here.
public void AllowThisBrowser(string endpoint, string p256dh, string auth) {
  SubscribeToPush(endpoint, p256dh, auth);
}

/// What the service worker shows when a push wakes it — the reader's own unread lines.
public List<NotificationLine> WhatIsWaiting() {
  return UnreadNotificationLines(3);
}

A channel of your own#

public class ChatChannel : INotificationChannel {
  public string Key { get; } = "chat";
  public string Token = "";
  public bool IsReady() { return Token != ""; }
  public bool Reaches(Principal person) { return ChatHandle.Any(h => h.Person == person); }
  public void Send(Principal person, Notification n, string idempotencyKey) {
    // Say nothing the person may not read: a link to the app, read there as them.
    PostToChat(ChatHandle.Single(h => h.Person == person).Handle, "Something is waiting for you in the app.", idempotencyKey);
  }
}

See also#

Related

The Notifications kit — telling a person that something needs them

`Osysharp.Notifications` tells a person that something needs them — in the app, a bell with a live count and a list…

Records — what any record is called, where it opens, who may read it

`Records.*` answers facts about a row of ANY type from what the app declared — what it is called (`[Title]`), where it…

package.osy

The manifest that makes a git repository a publishable Osy# package. It names the package, says which of the…

declaring secrets (app.Secrets)

`app.Secrets` declares the named secrets your app uses — API keys, tokens, client secrets. Each is `new…

Http.*

Make an outbound HTTP call to a URL you build at runtime — a webhook, a third-party API, a discovered endpoint…

[Settings] and [Setting]: a settings section declared on its row, each field drawn by its type

Mark the row staff configure `[Settings("Title", Authorize = Policy)]` and each field on it `[Setting("Label")]`, and…