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

> 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.

<!-- id: ui-notifications-web-push · area: ui · stability: preview · html: https://osysharp.com/reference/ui/notifications-web-push/ -->

## Summary        {#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:

```osy syntax
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:ops@harbour.example" } ] };
```

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

## Signature      {#signature}
```osy syntax
// 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    {#description}

### When a channel is told   {#when}
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`](https://osysharp.com/reference/stdlib/records/), 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   {#payload}
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   {#wire}
| | |
|---|---|
| **Method, address** | `POST` the subscription's `endpoint` |
| **Body** | empty (`Content-Length: 0`) — no `Content-Encoding` |
| **`Authorization`** | `vapid t=<JWT>, k=<PublicKey>` (RFC 8292) |
| **the JWT** | header `{"typ":"JWT","alg":"ES256"}`; claims `aud` = the endpoint's origin (`https://fcm.googleapis.com`), `exp` = now + 12 h, `sub` = `Subject`; signed ES256 with `PrivateKey` |
| **`TTL`** | `TimeToLive` in seconds — 43200 by default |
| **`Urgency`** | `high` for a mention, else `normal` |
| **`Topic`** | the 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   {#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:

```js syntax
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   {#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`](https://osysharp.com/reference/function/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   {#settings}
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   {#egress}
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:

```bash syntax
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       {#examples}

### A studio that pushes to its writers   {#example-studio}
```osy title="Web Push named beside the bell, and what the browser calls" test app=ui-notifications-web-push
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:desk@studio.example" } ] };

/// 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   {#example-channel}
```osy title="an adapter: a chat message to a person's own channel" syntax
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       {#see-also}
- [The Notifications kit — telling a person that something needs them](https://osysharp.com/reference/ui/notifications-kit/) — the bell, mail and delivery a channel sits beside
- [Records — what any record is called, where it opens, who may read it](https://osysharp.com/reference/stdlib/records/) — `Records.MayRead`, asked at every try
- [package.osy](https://osysharp.com/reference/project/package/) — `egress consumer;` and the hosts an app grants
- [declaring secrets (app.Secrets)](https://osysharp.com/reference/config/secrets/) — where the VAPID private key lives
- [Http.*](https://osysharp.com/reference/http/facade/) — `Http.Post`, and a non-2xx as data
- [[Settings] and [Setting]: a settings section declared on its row, each field drawn by its type](https://osysharp.com/reference/ui/settings-declared/) — the personal settings page "Push to my devices" is on
- **`kits/notifications/tests/push.test.osy`** — every behaviour above as a test
