Files
puter/doc/push-client.md
Juan Fernando CastroandDaniel Salazar 768b52c10e refactor(push): push database and key names are written once, and the desktop reads its push record through puter.js (#4653)
* refactor(push): the database and key names are written once for the page and both workers

pushNames.js holds the puter-push database name, its stores, key prefixes
and the subscription-changed message. pushStore.js re-exports them.

push-sw.js and the GUI's sw.js are served as they are (push-sw.js also
from npm's src/), so neither can import the module. Each carries a block
generated from pushNames.js by tools/pushWorkerNames.mjs. The puter.js
webpack build and the GUI build fail while either block is stale, and a
test compares the names in both worker sources with the page module's.

* refactor(push): the desktop reads the confirmed endpoint and the mark through puter.js

puter.js now records the endpoint the server confirmed, and clears the
subscription-changed mark, inside the Puter GUI as on a website. Three
internal methods give the desktop what it kept itself: _webPushRecord()
reads both, _noteWebPushSynced() records an endpoint a status check
confirmed, and _dropRemovedWebPush() ends a removed subscription and
forgets its receipt and the mark.

webPushClient.js no longer opens the puter-push database or keeps its
own localStorage record. An endpoint an earlier build kept there is read
while puter.js has none, and removed once puter.js records one, so an
already synced browser keeps its status without registering again. With
a puter.js that lacks the methods, the client reads nothing from it and
keeps the old record.

* refactor(push): one-line comments on the push names and the record methods

* fix(push): the worker names check reads CRLF checkouts, lives in tools/ and runs in PR CI

The block helper moves to tools/pushNamesBlock.mjs, so it isn't part of
the published puter.js sources. It compares and rewrites on LF text and
writes back the file's own line endings. Both workers are pinned to LF
in .gitattributes. The puter.js tests run when the GUI's sw.js or its
build changes, and the GUI build checks sw.js before anything else.

* fix(push): the desktop keeps a removed browser off with a puter.js that has no push record

The desktop loads puter.js from its own URL, so it can run one without
_webPushRecord(). The client then uses pushStore.js's helpers itself: it
reads and clears the subscription-changed mark, ends a removed
subscription and forgets its receipt and the mark, clears the mark after
enable(), and keeps the confirmed endpoint in localStorage as before.

_noteWebPushSynced() resolves whether it recorded the endpoint, and the
localStorage endpoint is removed only after puter.js has it. A cached
status reads only the mark before answering. The accessors carry JSDoc
types.

* fix(push): the removed-elsewhere check also asks about the endpoint in localStorage

When loads alternate between puter.js versions, localStorage can hold a
newer confirmed endpoint than puter.js does. The background check now
asks about both, with the mark's old endpoint, before registering.

* fix(push): with an older puter.js the desktop also asks about the endpoint puter.js recorded

Once puter.js has recorded the confirmed endpoint, the desktop drops its
localStorage copy. A later load that runs an older puter.js then read
neither, so a browser that lost its subscription after being removed in
Puter could register again. The fallback now reads puter.js's record from
the store directly.

* refactor(puter-js): the push record reads use try/catch instead of .catch()

---------

Co-authored-by: Daniel Salazar <daniel.salazar@puter.com>
2026-11-16 09:06:23 -07:00

12 KiB

Browser push client

Puter's desktop shows pushes through /sw.js. Core shows Settings → Notifications only when the pushEnabled gui param is true; core never sets it. The worker is registered only when push is turned on in the browser, and a load removes one left without a subscription. A backend extension that delivers pushes sets it with services.homepage.setGuiParam('pushEnabled', true) and can load its own code into the worker with services.homepage.registerServiceWorkerScript(path).

Core subscribes the browser to a push service only when the server also publishes pushWebPushKey (see Built-in Web Push client), and it has no /push/* routes of its own. The device, app, preference and subscription endpoints below come from that extension. On a deployment without one, such as most self-hosted servers, they answer core's plain 404 (code: 'not_found'), which puter.notifications reports as push_unavailable and the Notifications tab shows as unavailable. A device the extension can't find is device_not_found.

Push payload

sw.js reads the push's JSON body. The message is its puter field, or data.puter for services that only carry string data, as an object or a JSON string:

{ uid?: string; title?: string; body?: string; icon?: string; group?: string;
  target?: { app?: string; path?: string }; data?: unknown; channel?: string;
  type?: 'challenge'; challenge?: string }

uid is the notification's uid, a later push with the same group replaces the one showing, and target and data reach the app when the user taps it.

When the browser replaces the subscription (pushsubscriptionchange), sw.js keeps the new one, or subscribes again with Puter's stored key when the browser gave none and the event, the receipt or an earlier mark names the subscription that went. It writes puter:subscription-changed:<scope> to the puter-push IndexedDB as { at, oldEndpoint }, the old endpoint kept from an earlier mark no page handled yet, else taken from the event or from the receipt, forgets the receipt kept for that scope, and posts { type: 'puter-push-subscription-changed' } to every open window on Puter's origin. The worker has no token or session, so an open page runs helpers/pushSync.js on that message, after any run already in flight, and a later load does the same through the marker.

The database, store and key names are written once, in puter.js's modules/notifications/lib/pushNames.js. sw.js and puter.js's push-sw.js are served as they are, so each carries a generated copy: run node tools/pushWorkerNames.mjs after changing the names. The puter.js and GUI builds fail while a copy is stale.

Receipts

Before a notification is pushed, the server asks the open clients whether they received it live. It sends notif.receipt with { uid } on the user's sockets for the app that sent it, or on the desktop's sockets for Puter's own notifications. The SDK remembers the uids its page received through onNotification(), onPush() or the desktop's feed, and answers once its page has that notification, or with { received: false } when it never gets it. The server waits up to 5 seconds (notificationAckTimeoutMs).

An answer carries visibilityState and focused as they were when the page received the notification. Pages never show a browser notification themselves; pushes do.

  • An answer from a page that was visible and focused stops the push (handled on notif.delivery.settled). An older client that doesn't send focused counts while visible.
  • Otherwise the notification is pushed, to every browser the user subscribed. A website's pushes go only to the browsers that subscribed through its own worker, never to Puter's /sw.js. An app inside the desktop pushes through /sw.js, which shows the app's name and icon.
  • A client that can't answer, such as an older puter.js, doesn't hold the push back.

The ask reaches only the sockets in the asking region. So that other regions hear about a page too, a page that receives a notification live while visible and focused also sends notif.handled with { uid } on the socket it came on. Core relays it as the node-local notif.handled event with the socket's user and app, at most 60 a minute per user; an extension that delivers pushes decides what to do with it.

Registering

The registry is in src/gui/src/helpers/pushClient.js. A service script registers its client like this:

service_script(async (api) => {
    api.use()['push.registerPushClient']?.(client);
});

use(id) throws when nothing is registered under id, so the form above also runs on a Puter version without the registry and does nothing there. Any script that runs after the GUI bundle can call use()['push.registerPushClient']?.(client) the same way. Registering again replaces the client. Registering dispatches push-client-registered on window, and an open Notifications tab redraws.

With no client registered, the tab says push notifications aren't available in this browser.

Built-in Web Push client

When the server also sets the pushWebPushKey gui param (a VAPID public key), core registers its own client (webPushClient.js) unless an extension registered one first. It uses puter.notifications.enable() / disable(), the same standard Web Push flow apps use on their own origins:

  1. GET /push/web/key for the key, then pushManager.subscribe() on the /sw.js registration.
  2. POST /push/web/subscriptions { subscription }. A subscription the server already has answers { status: 'active' }. A new one answers { status: 'pending' }, and the server sends it a push with { type: 'challenge', challenge }.
  3. The worker shows that push and posts { type: 'puter-push-challenge', challenge } to the origin's windows; the page sends it to POST /push/web/subscriptions/verify. The device is registered once the page hands the confirmation back.
  4. DELETE /push/web/subscriptions { endpoint } removes it.

Apps on their own origin do the same through push-sw.js, which they import into their own worker. A subscription made with an app token is the app's: its pushes are that app's notifications only.

Interface

interface PushClient {
    enable(options?: { background?: boolean }): Promise<{ deviceUid: string }>;
    disable(): Promise<void>;
    status(options?: { cached?: boolean }): Promise<{
        permission: 'default' | 'granted' | 'denied';
        registered: boolean;
        deviceUid?: string;
    }>;
}
  • enable() may ask for notification permission, so core calls it from a click: Turn on in the Notifications tab, Allow on a permission prompt that includes notifications:push while this browser is off, and the "Turn on notifications" button of the /action/enable-push popup and the matching desktop dialog (UIEnablePushDialog). Core also calls it without a click, from helpers/pushSync.js, when Notification.permission is already granted, status() reports the browser as not registered, the user has not turned push off in this browser, and an app may push to Puter's devices (puterDevices in GET /push/apps); the browser does not prompt then. That call passes { background: true }: a browser the user removed in Puter stays removed, and the built-in client rejects with code push_device_removed, after which core records the browser as turned off. Before a background call the built-in client asks POST /push/web/subscriptions/status about every earlier endpoint it knows: the marker's oldEndpoint and the last endpoint the server confirmed for the signed-in user. puter.js keeps that endpoint in the puter-push IndexedDB (puter:synced:<user uuid>), from each registration and from each status() the server answers active, and the client reads both through it. An endpoint kept in localStorage (puter.push.last-endpoint:<user uuid>) is asked about too, and removed once puter.js has recorded the same endpoint. With a puter.js that has no push record methods, the client reads and clears the marker in the puter-push IndexedDB itself, reads the endpoint a newer puter.js recorded there on an earlier load, ends a removed subscription and forgets its receipt, and keeps the confirmed endpoint in that localStorage key. On a 429 it registers nothing and rejects with too_many_requests, which the sync reports as later, keeping the marker for the next run. When any answer is removed, puter.js ends the current subscription in the browser and forgets its receipt and the marker, and the client rejects with push_device_removed, so a subscription change or a dropped subscription never brings back a browser removed from another device. A click renews it as before. For a click the built-in client runs puter.notifications.enable(), which subscribes with the /sw.js registration and registers the browser through the Web Push flow above (platform: 'webpush'); in the background it runs puter.notifications.enable({ background: true }), the same registration without a permission prompt, without replacing a removed subscription and without opening Puter's sign-in. A puter.js without that option would run the call as a click, so the client checks _enableTakesBackground first and otherwise calls _enableWebPush with { background: true }. puter.js clears the subscription-changed marker once the server confirms the subscription. The client then resolves the uid of this browser's webpush device from listDevices(). It rejects when permission is refused or the browser wasn't registered.
  • disable() runs puter.notifications.disable(), which sends DELETE /push/web/subscriptions { endpoint } and ends the browser's subscription. The tab calls it for Turn off, and for Remove on the device marked as this browser. Remove on any other device is DELETE /push/devices/:uid.
  • status() reports the state without prompting. permission is Notification.permission. registered is true when this browser has a device registered for the signed-in user and POST /push/web/subscriptions/status answers active for the current subscription's endpoint, and deviceUid is that device's uid. A server that can't answer leaves the device match alone, and so does an unknown for an endpoint enable() registered in this page in the last 5 minutes, since that check can trail a registration. While the subscription-changed marker is set, registered is false. With { cached: true } a client may answer with the last registered state it read in this page. Core passes it for the silent registration on app launch and for an app's puter.notifications.status(); the Notifications tab and the push dialogs read fresh. The built-in client keeps that state in memory for the same user and subscription for up to 5 minutes, from enable() or once the server answered active for the endpoint, and answers from it without either request. Reads of the same user and endpoint share one real check while it is in flight. It drops it on disable(), a failed enable(), an unregistered answer, a set subscription-changed marker, and the worker's puter-push-subscription-changed message, so a new page load always asks the server. Whether the calling app may push is checked on every call, against a GET /push/apps answer the page reuses for 30 seconds and drops on enable(), disable(), a grant, a revoke and a user change. When it can't be read, or leaves the app out, the grant alone counts.

After enable() resolves, the tab calls POST /push/devices/:uid/test and asks the user whether a notification showed up.

The tab also reads GET /push/apps and GET/POST /push/preferences.

Core keeps its own record of a browser the user turned off, puter.push.browser-off:<user uuid> in localStorage, written by Turn off, by Remove on this browser's device, and by a silent registration the server refuses with push_device_removed, and cleared when enable() resolves. The silent registration above skips a browser with that record, so a device removed here or from another device stays removed until the user turns it on from a click, while a new sign-in in a browser that already allows notifications registers again.