From 768b52c10e5215aae797b815a957ac6c1919ce95 Mon Sep 17 00:00:00 2001 From: Juan Fernando Castro Date: Mon, 16 Nov 2026 11:06:23 -0500 Subject: [PATCH] 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 --- .gitattributes | 2 + .github/workflows/puterjs-tests.yaml | 2 + doc/push-client.md | 4 +- src/gui/src/helpers/webPushClient.js | 102 ++++++---- src/gui/src/helpers/webPushClient.test.js | 191 +++++++++++++++--- src/gui/src/sw.js | 36 ++-- src/gui/src/sw.test.js | 17 -- src/gui/utils.js | 4 + .../src/modules/notifications/index.js | 94 ++++++++- .../modules/notifications/lib/pushNames.js | 21 ++ .../notifications/lib/pushNames.test.js | 53 +++++ .../modules/notifications/lib/pushStore.js | 30 +-- .../src/modules/notifications/webPush.test.js | 82 ++++++++ src/puter-js/src/push-sw.js | 56 ++--- src/puter-js/webpack.config.js | 7 +- tools/pushNamesBlock.mjs | 29 +++ tools/pushWorkerNames.mjs | 18 ++ 17 files changed, 589 insertions(+), 159 deletions(-) create mode 100644 src/puter-js/src/modules/notifications/lib/pushNames.js create mode 100644 src/puter-js/src/modules/notifications/lib/pushNames.test.js create mode 100644 tools/pushNamesBlock.mjs create mode 100644 tools/pushWorkerNames.mjs diff --git a/.gitattributes b/.gitattributes index dfe077042..b050389e6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ # Auto detect text files and perform LF normalization * text=auto +src/gui/src/sw.js text eol=lf +src/puter-js/src/push-sw.js text eol=lf diff --git a/.github/workflows/puterjs-tests.yaml b/.github/workflows/puterjs-tests.yaml index 18bce42c7..5f0e935cf 100644 --- a/.github/workflows/puterjs-tests.yaml +++ b/.github/workflows/puterjs-tests.yaml @@ -34,6 +34,8 @@ jobs: - 'src/worker/**' - 'src/backend/testUtil.ts' - 'src/backend/vitest.config.ts' + - 'src/gui/src/sw.js' + - 'src/gui/utils.js' - 'tools/**' - 'package.json' - 'package-lock.json' diff --git a/doc/push-client.md b/doc/push-client.md index 30bb13b7d..d4e937d66 100644 --- a/doc/push-client.md +++ b/doc/push-client.md @@ -18,6 +18,8 @@ Core subscribes the browser to a push service only when the server also publishe 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:` 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`). @@ -69,7 +71,7 @@ interface PushClient { } ``` -- `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 answered `active` for (`puter.push.last-endpoint:` in `localStorage`). 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`, it ends the current subscription in the browser, clears the marker and 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 }`. It then resolves the `uid` of this browser's `webpush` device from `listDevices()` and clears the subscription-changed marker. It rejects when permission is refused or the browser wasn't registered. +- `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:`), 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:`) 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. diff --git a/src/gui/src/helpers/webPushClient.js b/src/gui/src/helpers/webPushClient.js index 189869a86..01926a9d5 100644 --- a/src/gui/src/helpers/webPushClient.js +++ b/src/gui/src/helpers/webPushClient.js @@ -24,6 +24,7 @@ import { RECEIPT_PREFIX, SUBSCRIPTION_CHANGED_MESSAGE, SUBSCRIPTION_CHANGED_PREFIX, + SYNCED_PREFIX, idbDelete, idbGet, } from '../../../puter-js/src/modules/notifications/lib/pushStore.js'; @@ -32,7 +33,7 @@ import { forgetPushApps, webPushEndpointState } from './notificationApi.js'; /** `/sw.js` as puter.js registers it, for a puter.js whose `enable()` has no `background`. */ const GUI_WORKER = { url: '/sw.js', scope: '/' }; -/** The endpoint the server last confirmed here for each user, in `localStorage`. */ +/** Per user, the confirmed endpoint when puter.js has no push record to keep it. */ export const LAST_ENDPOINT_PREFIX = 'puter.push.last-endpoint:'; const removedError = () => Object.assign(new Error('this browser was removed from push in Puter'), { code: 'push_device_removed' }); @@ -82,56 +83,73 @@ export const webPushClient = ({ return devices.find((d) => d.current && d.platform === 'webpush') ?? null; }; const registration = async () => await nav.serviceWorker?.getRegistration('/'); - /** The worker's mark for a replaced subscription, else null. */ - const marker = async (scope) => { - try { - return (await idbGet(HANDLERS_STORE, SUBSCRIPTION_CHANGED_PREFIX + scope, idb)) ?? null; - } catch ( e ) { - return null; - } - }; - const rememberEndpoint = (endpoint) => { - const user = userUid(); - if ( ! user ) return; - try { - storage.setItem(LAST_ENDPOINT_PREFIX + user, endpoint); - } catch ( e ) { - // Only the removed-elsewhere check below reads it. - } - }; - const lastEndpoint = () => { - try { - return storage.getItem(LAST_ENDPOINT_PREFIX + userUid()); - } catch ( e ) { - return null; - } - }; - const clearChanged = async () => { + const endpointKey = (user) => LAST_ENDPOINT_PREFIX + user; + // Without puter.js's push record, the client reads and clears the store itself. + const viaSdk = () => typeof notifications._webPushRecord === 'function'; + const directMark = async () => { try { const scope = (await registration())?.scope; - if ( scope ) await idbDelete(HANDLERS_STORE, SUBSCRIPTION_CHANGED_PREFIX + scope, idb); + return scope ? (await idbGet(HANDLERS_STORE, SUBSCRIPTION_CHANGED_PREFIX + scope, idb)) ?? null : null; + } catch ( e ) { + return null; + } + }; + const directForget = async (prefix) => { + try { + const scope = (await registration())?.scope; + if ( scope ) await idbDelete(HANDLERS_STORE, prefix + scope, idb); } catch ( e ) { // The next load registers again. } }; + // A newer puter.js on an earlier load may have kept the endpoint only there. + const directSynced = async () => { + try { + const user = userUid(); + const synced = user ? await idbGet(HANDLERS_STORE, SYNCED_PREFIX + user, idb) : null; + return typeof synced?.endpoint === 'string' && synced.endpoint ? synced.endpoint : null; + } catch ( e ) { + return null; + } + }; + const pushRecord = async ({ endpoint = true } = {}) => (viaSdk() + ? await notifications._webPushRecord({ endpoint }) + : { endpoint: endpoint ? await directSynced() : null, changed: await directMark() }); + const storedEndpoint = () => { + try { + return storage.getItem(endpointKey(userUid())); + } catch ( e ) { + return null; + } + }; + /** Keeps `endpoint` as the one the server confirmed for `user`. */ + const noteConfirmed = async (user, endpoint) => { + try { + if ( ! viaSdk() ) return storage.setItem(endpointKey(user), endpoint); + const known = (await notifications._webPushRecord()).endpoint; + if ( known !== endpoint && ! await notifications._noteWebPushSynced(endpoint) ) return; + storage.removeItem(endpointKey(user)); + } catch ( e ) { + // Only the removed-elsewhere check reads it. + } + }; /** `'removed'` when the user removed any earlier endpoint of this browser, ending the subscription here; `'busy'` on a 429. */ const removedElsewhere = async () => { - const worker = await registration(); - const mark = worker?.scope ? await marker(worker.scope) : null; - const earlier = [...new Set([mark?.oldEndpoint, lastEndpoint()].filter((e) => typeof e === 'string' && e))]; - const states = await Promise.all(earlier.map((endpoint) => endpointState(endpoint))); + const { endpoint, changed } = await pushRecord(); + const earlier = [...new Set([changed?.oldEndpoint, endpoint, storedEndpoint()].filter((e) => typeof e === 'string' && e))]; + const states = await Promise.all(earlier.map((e) => endpointState(e))); if ( ! states.includes('removed') ) return states.includes('busy') ? 'busy' : null; + if ( viaSdk() ) { + await notifications._dropRemovedWebPush(); + return 'removed'; + } try { - await (await worker?.pushManager?.getSubscription())?.unsubscribe(); + await (await (await registration())?.pushManager?.getSubscription())?.unsubscribe(); } catch ( e ) { // The next background run asks again. } - try { - if ( worker?.scope ) await idbDelete(HANDLERS_STORE, RECEIPT_PREFIX + worker.scope, idb); - } catch ( e ) { - // A receipt is only sent for its own endpoint. - } - await clearChanged(); + await directForget(RECEIPT_PREFIX); + await directForget(SUBSCRIPTION_CHANGED_PREFIX); return 'removed'; }; return { @@ -159,10 +177,10 @@ export const webPushClient = ({ const user = userUid(); const device = await currentDevice(); if ( ! device ) throw new Error('this browser was not registered'); - await clearChanged(); + if ( ! viaSdk() ) await directForget(SUBSCRIPTION_CHANGED_PREFIX); const subscription = await (await registration())?.pushManager?.getSubscription(); if ( subscription?.endpoint && user === userUid() ) { - rememberEndpoint(subscription.endpoint); + if ( user ) await noteConfirmed(user, subscription.endpoint); if ( reading === generation && user ) { lastOn = { userUid: user, endpoint: subscription.endpoint, deviceUid: device.uid, at: now(), enabled: true }; } @@ -192,7 +210,7 @@ export const webPushClient = ({ return { permission, registered: false }; } // A subscription the browser replaced is registered again in full. - if ( await marker(worker.scope) != null ) { + if ( (await pushRecord({ endpoint: false })).changed != null ) { forgetOn(); return { permission, registered: false }; } @@ -208,7 +226,7 @@ export const webPushClient = ({ // The server's answer can trail what `enable()` just registered in this page. const trailing = state === 'unknown' && kept && lastOn?.enabled === true; const registered = !! device && (state === 'active' || state === null || state === 'busy' || trailing); - if ( registered && state === 'active' && user === userUid() ) rememberEndpoint(subscription.endpoint); + if ( registered && state === 'active' && user && user === userUid() ) await noteConfirmed(user, subscription.endpoint); if ( reading === generation && ! trailing ) { // Only an `on` the server confirmed for this endpoint and user is kept. lastOn = registered && state === 'active' && user && user === userUid() diff --git a/src/gui/src/helpers/webPushClient.test.js b/src/gui/src/helpers/webPushClient.test.js index 5f02750c1..10336e295 100644 --- a/src/gui/src/helpers/webPushClient.test.js +++ b/src/gui/src/helpers/webPushClient.test.js @@ -21,6 +21,7 @@ import { describe, expect, it, vi } from 'vitest'; import { RECEIPT_PREFIX, SUBSCRIPTION_CHANGED_PREFIX, + SYNCED_PREFIX, } from '../../../puter-js/src/modules/notifications/lib/pushStore.js'; import { cachedPushApps } from './notificationApi.js'; import { registerPushClient } from './pushClient.js'; @@ -30,6 +31,8 @@ import { LAST_ENDPOINT_PREFIX, ON_KEPT_MS, webPushClient } from './webPushClient const SCOPE = 'https://puter.test/'; const LAST_ENDPOINT_KEY = `${LAST_ENDPOINT_PREFIX}u-1`; const CHANGED = `${SUBSCRIPTION_CHANGED_PREFIX}${SCOPE}`; +const RECEIPT = `${RECEIPT_PREFIX}${SCOPE}`; +const synced = (endpoint, user = 'u-1') => ({ [`${SYNCED_PREFIX}${user}`]: { endpoint, at: 1 } }); /** `localStorage` over a Map. */ const fakeStorage = (entries = {}) => { @@ -58,16 +61,39 @@ const fakeIdb = (entries = {}) => { }; }; -const make = ({ on = true, devices = [], permission = 'granted', subscription = { endpoint: 'https://push.test/1' }, user = 'u-1', serverState = 'active', idb = fakeIdb(), storage = fakeStorage(), takesBackground = true } = {}) => { +/** A client over a stand-in puter.js that keeps its push record in a Map. */ +const make = ({ on = true, devices = [], permission = 'granted', subscription = { endpoint: 'https://push.test/1' }, user = 'u-1', serverState = 'active', kept = {}, storage = fakeStorage(), idb = fakeIdb(), oldSdk = false, takesBackground = true } = {}) => { + const sdk = new Map(Object.entries(kept)); + const state = { subscription, user, serverState, now: 0 }; const notifications = { - enable: vi.fn(async () => on), + enable: vi.fn(async () => { + if ( on ) { + sdk.set(`${SYNCED_PREFIX}${state.user}`, { endpoint: state.subscription?.endpoint, at: state.now }); + sdk.delete(CHANGED); + } + return on; + }), _enableWebPush: vi.fn(async () => {}), ...(takesBackground ? { _enableTakesBackground: true } : {}), disable: vi.fn(async () => true), listDevices: vi.fn(async () => devices), + _webPushRecord: vi.fn(async ({ endpoint = true } = {}) => ({ endpoint: endpoint ? sdk.get(`${SYNCED_PREFIX}${state.user}`)?.endpoint ?? null : null, changed: sdk.get(CHANGED) ?? null })), + _noteWebPushSynced: vi.fn(async (endpoint) => { + sdk.set(`${SYNCED_PREFIX}${state.user}`, { endpoint, at: state.now }); + return true; + }), + _dropRemovedWebPush: vi.fn(async () => { + await state.subscription?.unsubscribe?.(); + sdk.delete(RECEIPT); + sdk.delete(CHANGED); + }), }; + if ( oldSdk ) { + delete notifications._webPushRecord; + delete notifications._noteWebPushSynced; + delete notifications._dropRemovedWebPush; + } const listeners = new Set(); - const state = { subscription, user, serverState, now: 0 }; const nav = { serviceWorker: { getRegistration: vi.fn(async () => ({ scope: SCOPE, pushManager: { getSubscription: async () => state.subscription } })), @@ -79,7 +105,7 @@ const make = ({ on = true, devices = [], permission = 'granted', subscription = }; const endpointState = vi.fn(async () => state.serverState); const client = webPushClient({ notifications, NotificationApi: { permission }, nav, userUid: () => state.user, idb, endpointState, storage, now: () => state.now }); - return { notifications, client, post, state, endpointState, idb, storage }; + return { notifications, client, post, state, endpointState, sdk, storage, idb }; }; const current = { uid: 'd1', platform: 'webpush', current: true }; @@ -114,19 +140,18 @@ describe('webPushClient', () => { }); it('is not registered once the worker marked the subscription replaced, until enable() registers it', async () => { - const idb = fakeIdb({ [CHANGED]: 1 }); - const { client, endpointState } = make({ devices: [current], idb }); + const { client, endpointState, sdk } = make({ devices: [current], kept: { [CHANGED]: 1 } }); await expect(client.status()).resolves.toEqual({ permission: 'granted', registered: false }); expect(endpointState).not.toHaveBeenCalled(); await expect(client.enable()).resolves.toEqual({ deviceUid: 'd1' }); - expect(idb.map.has(CHANGED)).toBe(false); + expect(sdk.has(CHANGED)).toBe(false); await expect(client.status()).resolves.toEqual({ permission: 'granted', registered: true, deviceUid: 'd1' }); }); it('has the next load register a replaced subscription in full', async () => { globalThis.gui_params = { pushEnabled: true }; - const { client, notifications } = make({ devices: [current], idb: fakeIdb({ [CHANGED]: 1 }) }); + const { client, notifications } = make({ devices: [current], kept: { [CHANGED]: 1 } }); registerPushClient(client); const storage = { getItem: () => null, setItem: () => {}, removeItem: () => {} }; await expect(syncBrowserPush({}, { NotificationApi: { permission: 'granted' }, userUid: 'u-1', storage, holdsPush: async () => true })).resolves.toBe('on'); @@ -186,6 +211,62 @@ describe('webPushClient', () => { }); }); +describe('webPushClient and puter.js`s push record', () => { + const ENDPOINT = 'https://push.test/1'; + const spiedStorage = (entries) => { + const storage = fakeStorage(entries); + storage.setItem = vi.fn(storage.setItem); + return storage; + }; + + it('reads the confirmed endpoint and the mark through puter.js and keeps no localStorage record', async () => { + const storage = spiedStorage(); + const { client, notifications } = make({ devices: [current], storage }); + await expect(client.status()).resolves.toEqual({ permission: 'granted', registered: true, deviceUid: 'd1' }); + expect(notifications._webPushRecord).toHaveBeenCalled(); + expect(notifications._noteWebPushSynced).toHaveBeenCalledWith(ENDPOINT); + await client.enable({ background: true }); + expect(storage.setItem).not.toHaveBeenCalled(); + expect(storage.map.size).toBe(0); + + notifications._noteWebPushSynced.mockClear(); + await client.status(); + expect(notifications._noteWebPushSynced).not.toHaveBeenCalled(); + }); + + it('moves an earlier build`s localStorage endpoint into puter.js on a confirmed status, with no new registration', async () => { + globalThis.gui_params = { pushEnabled: true }; + const storage = spiedStorage({ [LAST_ENDPOINT_KEY]: ENDPOINT }); + const made = make({ devices: [current], storage }); + registerPushClient(made.client); + await expect(syncBrowserPush({}, { NotificationApi: { permission: 'granted' }, userUid: 'u-1', storage, holdsPush: async () => true })).resolves.toBe('on'); + expect(made.notifications.enable).not.toHaveBeenCalled(); + expect(made.notifications._noteWebPushSynced).toHaveBeenCalledWith(ENDPOINT); + await expect(made.notifications._webPushRecord()).resolves.toEqual({ endpoint: ENDPOINT, changed: null }); + expect(storage.map.has(LAST_ENDPOINT_KEY)).toBe(false); + expect(storage.setItem).not.toHaveBeenCalled(); + }); + + it('deletes the localStorage endpoint only once puter.js recorded the endpoint', async () => { + const storage = spiedStorage({ [LAST_ENDPOINT_KEY]: ENDPOINT }); + const { client, notifications } = make({ devices: [current], storage }); + notifications._noteWebPushSynced.mockResolvedValueOnce(false); + await client.status(); + expect(notifications._noteWebPushSynced).toHaveBeenCalledWith(ENDPOINT); + expect(storage.map.get(LAST_ENDPOINT_KEY)).toBe(ENDPOINT); + await client.status(); + expect(storage.map.has(LAST_ENDPOINT_KEY)).toBe(false); + }); + + it('reads only the mark, not the endpoint, before a cached answer', async () => { + const { client, notifications } = make({ devices: [current] }); + await client.status(); + notifications._webPushRecord.mockClear(); + await client.status({ cached: true }); + expect(notifications._webPushRecord.mock.calls).toEqual([[{ endpoint: false }]]); + }); +}); + describe('webPushClient status with cached', () => { const on = { permission: 'granted', registered: true, deviceUid: 'd1' }; @@ -287,9 +368,9 @@ describe('webPushClient status with cached', () => { it('ignores the last on while the worker`s subscription-changed mark is set', async () => { const made = await readOn(); - made.idb.map.set(CHANGED, 1); + made.sdk.set(CHANGED, 1); await expect(made.client.status({ cached: true })).resolves.toEqual({ permission: 'granted', registered: false }); - made.idb.map.delete(CHANGED); + made.sdk.delete(CHANGED); made.endpointState.mockClear(); await made.client.status({ cached: true }); expect(made.notifications.listDevices).toHaveBeenCalledTimes(1); @@ -382,50 +463,67 @@ describe('webPushClient and a browser removed from another device', () => { }; it('stays off after a subscription change, and records it as turned off', async () => { - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD } } }); await expect(sync(made.storage)).resolves.toBe('removed'); expect(made.endpointState).toHaveBeenCalledWith(OLD); expect(made.notifications.enable).not.toHaveBeenCalled(); expect(NEW.unsubscribe).toHaveBeenCalledTimes(1); - expect(made.idb.map.has(CHANGED)).toBe(false); + expect(made.sdk.has(CHANGED)).toBe(false); expect(made.storage.map.get(OPT_OUT)).toBe('1'); await expect(sync(made.storage)).resolves.toBe('opted_out'); }); - it('forgets the removed endpoint`s receipt when it stays off', async () => { - const RECEIPT = `${RECEIPT_PREFIX}${SCOPE}`; - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD }, [RECEIPT]: { endpoint: OLD, receipt: 'r.sig' } }) }); + it('has puter.js forget the removed endpoint`s receipt when it stays off', async () => { + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD }, [RECEIPT]: { endpoint: OLD, receipt: 'r.sig' } } }); await expect(sync(made.storage)).resolves.toBe('removed'); - expect(made.idb.map.has(RECEIPT)).toBe(false); + expect(made.notifications._dropRemovedWebPush).toHaveBeenCalledTimes(1); + expect(made.sdk.has(RECEIPT)).toBe(false); }); - it('stays off after the browser dropped the subscription, from the last endpoint the server confirmed', async () => { + it('stays off after the browser dropped the subscription, from the endpoint puter.js recorded', async () => { + const made = removedElsewhere({ subscription: null, kept: synced(OLD) }); + await expect(sync(made.storage)).resolves.toBe('removed'); + expect(made.endpointState).toHaveBeenCalledWith(OLD); + expect(made.notifications.enable).not.toHaveBeenCalled(); + expect(made.storage.map.get(OPT_OUT)).toBe('1'); + }); + + it('stays off from the endpoint an earlier build kept in localStorage while puter.js has none', async () => { const made = removedElsewhere({ subscription: null, storage: fakeStorage({ [LAST_ENDPOINT_KEY]: OLD }) }); await expect(sync(made.storage)).resolves.toBe('removed'); expect(made.notifications.enable).not.toHaveBeenCalled(); expect(made.storage.map.get(OPT_OUT)).toBe('1'); }); + it('also asks about a newer endpoint only localStorage holds, and stays off when it was removed', async () => { + const made = removedElsewhere({ subscription: null, kept: synced('https://push.test/x'), storage: fakeStorage({ [LAST_ENDPOINT_KEY]: OLD }) }); + await expect(sync(made.storage)).resolves.toBe('removed'); + expect(made.endpointState).toHaveBeenCalledWith('https://push.test/x'); + expect(made.endpointState).toHaveBeenCalledWith(OLD); + expect(made.notifications.enable).not.toHaveBeenCalled(); + expect(made.storage.map.get(OPT_OUT)).toBe('1'); + }); + it('asks about the endpoint confirmed for the signed-in user only', async () => { - const made = removedElsewhere({ subscription: null, user: 'u-2', storage: fakeStorage({ [LAST_ENDPOINT_KEY]: OLD }) }); + const made = removedElsewhere({ subscription: null, user: 'u-2', kept: synced(OLD), storage: fakeStorage({ [LAST_ENDPOINT_KEY]: OLD }) }); made.notifications.listDevices.mockResolvedValue([current]); await expect(made.client.enable({ background: true })).resolves.toEqual({ deviceUid: 'd1' }); expect(made.endpointState).not.toHaveBeenCalledWith(OLD); }); it('turns back on from a click, which keeps the new endpoint', async () => { - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD } } }); await sync(made.storage); made.notifications.listDevices.mockResolvedValue([current]); await expect(made.client.enable()).resolves.toEqual({ deviceUid: 'd1' }); expect(made.notifications.enable).toHaveBeenCalledTimes(1); - expect(made.storage.map.get(LAST_ENDPOINT_KEY)).toBe(NEW.endpoint); + await expect(made.notifications._webPushRecord()).resolves.toEqual({ endpoint: NEW.endpoint, changed: null }); + expect(made.storage.map.has(LAST_ENDPOINT_KEY)).toBe(false); }); it('stays off when the removed endpoint is two subscription changes back', async () => { const made = removedElsewhere({ - idb: fakeIdb({ [CHANGED]: { at: 2, oldEndpoint: 'https://push.test/0b' } }), - storage: fakeStorage({ [LAST_ENDPOINT_KEY]: OLD }), + kept: { [CHANGED]: { at: 2, oldEndpoint: 'https://push.test/0b' }, ...synced(OLD) }, }); await expect(sync(made.storage)).resolves.toBe('removed'); expect(made.endpointState).toHaveBeenCalledWith('https://push.test/0b'); @@ -435,11 +533,11 @@ describe('webPushClient and a browser removed from another device', () => { }); it('registers nothing while the server answers 429, keeps the mark, and goes ahead on the next run', async () => { - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD } } }); made.endpointState.mockResolvedValue('busy'); await expect(sync(made.storage)).resolves.toBe('later'); expect(made.notifications.enable).not.toHaveBeenCalled(); - expect(made.idb.map.has(CHANGED)).toBe(true); + expect(made.sdk.has(CHANGED)).toBe(true); expect(made.storage.map.has(OPT_OUT)).toBe(false); made.endpointState.mockResolvedValue('unknown'); @@ -449,14 +547,55 @@ describe('webPushClient and a browser removed from another device', () => { }); it('turns on from a click while the server answers 429', async () => { - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD } } }); made.endpointState.mockResolvedValue('busy'); made.notifications.listDevices.mockResolvedValue([current]); await expect(made.client.enable()).resolves.toEqual({ deviceUid: 'd1' }); }); + describe('with a puter.js that has no push record', () => { + it('leaves a replaced subscription off when its old endpoint was removed elsewhere', async () => { + const made = removedElsewhere({ oldSdk: true, idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + await expect(sync(made.storage)).resolves.toBe('removed'); + expect(made.endpointState).toHaveBeenCalledWith(OLD); + expect(made.notifications.enable).not.toHaveBeenCalled(); + expect(made.storage.map.get(OPT_OUT)).toBe('1'); + }); + + it('stays off from the endpoint a newer puter.js recorded on an earlier load', async () => { + const made = removedElsewhere({ oldSdk: true, takesBackground: false, subscription: null, idb: fakeIdb(synced(OLD)) }); + await expect(sync(made.storage)).resolves.toBe('removed'); + expect(made.endpointState).toHaveBeenCalledWith(OLD); + expect(made.notifications._enableWebPush).not.toHaveBeenCalled(); + expect(made.notifications.enable).not.toHaveBeenCalled(); + expect(made.storage.map.get(OPT_OUT)).toBe('1'); + }); + + it('ends the subscription and forgets its receipt and the mark on a removed answer', async () => { + const made = removedElsewhere({ oldSdk: true, idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD }, [RECEIPT]: { endpoint: OLD, receipt: 'r.sig' } }) }); + await expect(sync(made.storage)).resolves.toBe('removed'); + expect(NEW.unsubscribe).toHaveBeenCalledTimes(1); + expect(made.idb.map.has(RECEIPT)).toBe(false); + expect(made.idb.map.has(CHANGED)).toBe(false); + }); + + it('clears the mark after enable(), so the next status reads on', async () => { + const made = make({ oldSdk: true, devices: [current], idb: fakeIdb({ [CHANGED]: { at: 1 } }) }); + await expect(made.client.status()).resolves.toEqual({ permission: 'granted', registered: false }); + await expect(made.client.enable()).resolves.toEqual({ deviceUid: 'd1' }); + expect(made.idb.map.has(CHANGED)).toBe(false); + await expect(made.client.status()).resolves.toEqual({ permission: 'granted', registered: true, deviceUid: 'd1' }); + }); + + it('keeps the confirmed endpoint in localStorage', async () => { + const made = make({ oldSdk: true, devices: [current] }); + await made.client.status(); + expect(made.storage.map.get(LAST_ENDPOINT_KEY)).toBe('https://push.test/1'); + }); + }); + it('registers in the background as before when the old endpoint wasn`t removed', async () => { - const made = removedElsewhere({ idb: fakeIdb({ [CHANGED]: { at: 1, oldEndpoint: OLD } }) }); + const made = removedElsewhere({ kept: { [CHANGED]: { at: 1, oldEndpoint: OLD } } }); made.endpointState.mockResolvedValue('unknown'); made.notifications.listDevices.mockResolvedValue([current]); await expect(sync(made.storage)).resolves.toBe('on'); diff --git a/src/gui/src/sw.js b/src/gui/src/sw.js index c5e336e86..dc4e5cbbc 100644 --- a/src/gui/src/sw.js +++ b/src/gui/src/sw.js @@ -30,20 +30,24 @@ const DEFAULT_TITLE = 'New notification'; const DEFAULT_ICON = '/favicons/android-icon-192x192.png'; const CLICK_MESSAGE = 'puter-notification-click'; const CLICK_ACK_MESSAGE = 'puter-notification-click-ack'; -const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; const CHALLENGE_MESSAGE = 'puter-push-challenge'; const CLICK_PARAM = 'puter.notification'; // Browsers allow openWindow only shortly after the click. const CLICK_ACK_BUDGET_MS = 600; const GUI_PATHS = /^\/(?:$|desktop(?:\/|$)|dashboard(?:\/|$)|app\/|settings(?:\/|$)|@)/; -// Entries puter.js keeps here (modules/notifications/lib/pushStore.js). -const DB_NAME = 'puter-push'; -const HANDLERS = 'handlers'; -const CLICKS = 'clicks'; -const SERVER_KEY = 'puter:server-key'; -const SERVER_KEYS = 'puter:server-keys'; -const CHANGED_PREFIX = 'puter:subscription-changed:'; +// Shared with puter.js: generated from lib/pushNames.js by tools/pushWorkerNames.mjs. +const CLICKS_STORE = 'clicks'; +const HANDLERS_STORE = 'handlers'; +const OPT_IN_PREFIX = 'puter:opt-in:'; +const PUSH_DB_NAME = 'puter-push'; const RECEIPT_PREFIX = 'puter:receipt:'; +const SERVER_KEYS_ENTRY = 'puter:server-keys'; +const SERVER_KEY_ENTRY = 'puter:server-key'; +const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; +const SUBSCRIPTION_CHANGED_PREFIX = 'puter:subscription-changed:'; +const SYNCED_PREFIX = 'puter:synced:'; +const TAP_BASE_PREFIX = 'puter:tap-base:'; +// End of generated names. const nonEmptyString = (value) => ( typeof value === 'string' && value.trim() !== '' ? value : undefined @@ -221,10 +225,10 @@ async function postToWindows (scope, message) { function openDB () { return new Promise((resolve, reject) => { - const req = indexedDB.open(DB_NAME, 1); + const req = indexedDB.open(PUSH_DB_NAME, 1); req.onupgradeneeded = () => { - req.result.createObjectStore(HANDLERS); - req.result.createObjectStore(CLICKS); + req.result.createObjectStore(HANDLERS_STORE); + req.result.createObjectStore(CLICKS_STORE); }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); @@ -235,7 +239,7 @@ async function idb (mode, action) { const db = await openDB(); try { return await new Promise((resolve, reject) => { - const req = action(db.transaction(HANDLERS, mode).objectStore(HANDLERS)); + const req = action(db.transaction(HANDLERS_STORE, mode).objectStore(HANDLERS_STORE)); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); @@ -262,8 +266,8 @@ function sameKey (buffer, value) { } async function puterKeys () { - const last = await idb('readonly', (s) => s.get(SERVER_KEY)); - const listed = await idb('readonly', (s) => s.get(SERVER_KEYS)); + const last = await idb('readonly', (s) => s.get(SERVER_KEY_ENTRY)); + const listed = await idb('readonly', (s) => s.get(SERVER_KEYS_ENTRY)); return [last, ...(Array.isArray(listed) ? listed : [])].filter((key) => nonEmptyString(key)); } @@ -276,12 +280,12 @@ async function keepSubscription (scope, event) { if ( old && ! keys.some((key) => sameKey(old, key)) ) return; // The page asks the server whether the old endpoint was removed before registering again. const receipt = await idb('readonly', (s) => s.get(RECEIPT_PREFIX + registration.scope)); - const earlier = await idb('readonly', (s) => s.get(CHANGED_PREFIX + registration.scope)); + const earlier = await idb('readonly', (s) => s.get(SUBSCRIPTION_CHANGED_PREFIX + registration.scope)); // A mark no page handled yet keeps the endpoint the server last knew. const oldEndpoint = nonEmptyString(earlier?.oldEndpoint) ?? nonEmptyString(event.oldSubscription?.endpoint) ?? nonEmptyString(receipt?.endpoint); - await idb('readwrite', (s) => s.put({ at: Date.now(), ...(oldEndpoint ? { oldEndpoint } : {}) }, CHANGED_PREFIX + registration.scope)); + await idb('readwrite', (s) => s.put({ at: Date.now(), ...(oldEndpoint ? { oldEndpoint } : {}) }, SUBSCRIPTION_CHANGED_PREFIX + registration.scope)); // The receipt names the old endpoint and keys. await idb('readwrite', (s) => s.delete(RECEIPT_PREFIX + registration.scope)); if ( event.newSubscription ) return; diff --git a/src/gui/src/sw.test.js b/src/gui/src/sw.test.js index 41eac6422..81b5501f2 100644 --- a/src/gui/src/sw.test.js +++ b/src/gui/src/sw.test.js @@ -22,11 +22,8 @@ import { fileURLToPath } from 'node:url'; import vm from 'node:vm'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { - HANDLERS_STORE, - PUSH_DB_NAME, RECEIPT_PREFIX, SERVER_KEY_ENTRY, - SERVER_KEYS_ENTRY, SUBSCRIPTION_CHANGED_MESSAGE, SUBSCRIPTION_CHANGED_PREFIX, } from '../../puter-js/src/modules/notifications/lib/pushStore.js'; @@ -368,20 +365,6 @@ describe('service worker pushsubscriptionchange', () => { const keyOf = (value) => ({ options: { applicationServerKey: new Uint8Array(Buffer.from(value, 'base64url')).buffer } }); const pushOn = { [SERVER_KEY_ENTRY]: KEY, [RECEIPT]: { endpoint: 'https://push.example/1', receipt: 'r.sig' } }; - it('keeps its own copy of the entries puter.js stores', () => { - for ( const [name, value] of Object.entries({ - DB_NAME: PUSH_DB_NAME, - HANDLERS: HANDLERS_STORE, - SERVER_KEY: SERVER_KEY_ENTRY, - SERVER_KEYS: SERVER_KEYS_ENTRY, - CHANGED_PREFIX: SUBSCRIPTION_CHANGED_PREFIX, - RECEIPT_PREFIX, - SUBSCRIPTION_CHANGED_MESSAGE, - }) ) { - expect(SOURCE).toContain(`const ${name} = '${value}';`); - } - }); - it('keeps the new subscription the browser gave, marks it with the old endpoint and forgets the receipt', async () => { const win = windowClient(`${ORIGIN}/desktop`); const worker = loadWorker({ windows: [win], handlers: pushOn }); diff --git a/src/gui/utils.js b/src/gui/utils.js index cd460c01b..2bcf813b1 100644 --- a/src/gui/utils.js +++ b/src/gui/utils.js @@ -26,6 +26,7 @@ import { lib_paths, css_paths, js_paths } from './src/static-assets.js'; import { fileURLToPath } from 'url'; import BaseConfig from './webpack/BaseConfig.cjs'; import { copyPdfThumbnailAssets } from './tools/copyPdfThumbnailAssets.js'; +import { hasPushNames } from '../../tools/pushNamesBlock.mjs'; // Polyfill __dirname, which doesn't exist in modules mode const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -53,6 +54,9 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); */ async function build (options) { const PUTER_ENV = process.env.PUTER_ENV || 'prod'; + if ( ! hasPushNames(fs.readFileSync(path.join(__dirname, 'src', 'sw.js'), 'utf8')) ) { + throw new Error('sw.js: stale push names; run node tools/pushWorkerNames.mjs'); + } // ----------------------------------------------- // Delete ./dist/ directory if it exists and create a new one // ----------------------------------------------- diff --git a/src/puter-js/src/modules/notifications/index.js b/src/puter-js/src/modules/notifications/index.js index ad90473c1..5a72142ee 100644 --- a/src/puter-js/src/modules/notifications/index.js +++ b/src/puter-js/src/modules/notifications/index.js @@ -912,15 +912,12 @@ export class NotificationsModule extends EventListener { /** Remembers the subscription the server confirmed, for the next loads. */ async #noteSynced(worker, endpoint) { - if (this.puter.env !== 'web') return; + await this._noteWebPushSynced(endpoint); + await this.#clearChanged(worker); + } + + async #clearChanged(worker) { try { - const uuid = await this.#userUuid(); - if (uuid) { - await idbPut(HANDLERS_STORE, SYNCED_PREFIX + uuid, { - endpoint, - at: Date.now(), - }); - } await idbDelete( HANDLERS_STORE, SUBSCRIPTION_CHANGED_PREFIX + workerScope(worker), @@ -930,6 +927,87 @@ export class NotificationsModule extends EventListener { } } + /** + * The worker's mark and, unless `endpoint` is false, the user's confirmed + * endpoint; nulls when unknown. + * + * @param {{ endpoint?: boolean }} [options] + * @returns {Promise<{ + * endpoint: string | null; + * changed: { at?: number; oldEndpoint?: string } | null; + * }>} + * @internal + */ + async _webPushRecord({ endpoint = true } = {}) { + const worker = workerFor(this.puter.env); + const readSynced = async () => { + if (!endpoint) return null; + try { + const uuid = await this.#userUuid(); + return uuid + ? await idbGet(HANDLERS_STORE, SYNCED_PREFIX + uuid) + : null; + } catch { + return null; + } + }; + const readChanged = async () => { + try { + return await idbGet( + HANDLERS_STORE, + SUBSCRIPTION_CHANGED_PREFIX + workerScope(worker), + ); + } catch { + return null; + } + }; + const [synced, changed] = await Promise.all([ + readSynced(), + readChanged(), + ]); + return { + endpoint: + typeof synced?.endpoint === 'string' && synced.endpoint + ? synced.endpoint + : null, + changed: changed ?? null, + }; + } + + /** + * Records `endpoint` as the one the server confirmed. + * + * @param {string} endpoint + * @returns {Promise} Whether it was recorded. + * @internal + */ + async _noteWebPushSynced(endpoint) { + try { + const uuid = await this.#userUuid(); + if (!uuid) return false; + await idbPut(HANDLERS_STORE, SYNCED_PREFIX + uuid, { + endpoint, + at: Date.now(), + }); + return true; + } catch { + // The next load registers again. + return false; + } + } + + /** + * Ends a subscription removed in Puter, with its receipt and mark. + * + * @returns {Promise} + * @internal + */ + async _dropRemovedWebPush() { + const worker = workerFor(this.puter.env); + await this.#dropRemoved(worker); + await this.#clearChanged(worker); + } + /** Ends a subscription left here without an opt-in, in the browser only. */ async #endUnwanted() { await withPushLock(async () => { diff --git a/src/puter-js/src/modules/notifications/lib/pushNames.js b/src/puter-js/src/modules/notifications/lib/pushNames.js new file mode 100644 index 000000000..b52bda029 --- /dev/null +++ b/src/puter-js/src/modules/notifications/lib/pushNames.js @@ -0,0 +1,21 @@ +// Both workers carry generated copies: run tools/pushWorkerNames.mjs after edits. + +export const PUSH_DB_NAME = 'puter-push'; +export const HANDLERS_STORE = 'handlers'; +export const CLICKS_STORE = 'clicks'; + +// Handlers-store keys no channel can take, so the database stays at version 1. +export const OPT_IN_PREFIX = 'puter:opt-in:'; +export const SERVER_KEY_ENTRY = 'puter:server-key'; +/** Every key the server named as Puter's, the current one first. */ +export const SERVER_KEYS_ENTRY = 'puter:server-keys'; +/** Per user: `{ endpoint, at }` of the subscription the server last confirmed. */ +export const SYNCED_PREFIX = 'puter:synced:'; +/** Per worker scope: set by a worker when a subscription is replaced. */ +export const SUBSCRIPTION_CHANGED_PREFIX = 'puter:subscription-changed:'; +/** Per worker scope: `{ endpoint, receipt }` the server last gave. */ +export const RECEIPT_PREFIX = 'puter:receipt:'; +/** Where a tap without a URL goes, per worker scope. */ +export const TAP_BASE_PREFIX = 'puter:tap-base:'; +/** What a worker posts when the browser replaced the push subscription. */ +export const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; diff --git a/src/puter-js/src/modules/notifications/lib/pushNames.test.js b/src/puter-js/src/modules/notifications/lib/pushNames.test.js new file mode 100644 index 000000000..4c9aad8e0 --- /dev/null +++ b/src/puter-js/src/modules/notifications/lib/pushNames.test.js @@ -0,0 +1,53 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import * as names from './pushNames.js'; +import { + hasPushNames, + withPushNames, +} from '../../../../../../tools/pushNamesBlock.mjs'; +import * as pushStore from './pushStore.js'; + +const WORKERS = { + 'push-sw.js': new URL('../../../push-sw.js', import.meta.url), + "the GUI's sw.js": new URL('../../../../../gui/src/sw.js', import.meta.url), +}; + +/** Every `const NAME = '...';` the source declares. */ +const declared = (source) => + Object.fromEntries( + [ + ...source + .replace(/\r\n/g, '\n') + .matchAll(/^\s*const ([A-Z_]+) = '([^']*)';$/gm), + ].map(([, name, value]) => [name, value]), + ); + +describe('the puter-push database names', () => { + it('are the ones the page module uses', () => { + expect(Object.keys(names).length).toBeGreaterThan(0); + for (const [name, value] of Object.entries(names)) + expect(pushStore[name]).toBe(value); + }); + + it.each(Object.entries(WORKERS))( + 'match the page module in %s', + (_label, url) => { + const source = readFileSync(url, 'utf8'); + expect(declared(source)).toMatchObject(names); + expect(hasPushNames(source)).toBe(true); + }, + ); + + it('read the same from a CRLF checkout, and keep its line endings when rewritten', () => { + const crlf = readFileSync(WORKERS['push-sw.js'], 'utf8').replace( + /\n/g, + '\r\n', + ); + expect(hasPushNames(crlf)).toBe(true); + expect(declared(crlf)).toMatchObject(names); + const stale = crlf.replace("'puter-push';", "'puter-push-0';"); + const rewritten = withPushNames(stale); + expect(rewritten).toBe(crlf); + expect(rewritten.replace(/\r\n/g, '')).not.toContain('\n'); + }); +}); diff --git a/src/puter-js/src/modules/notifications/lib/pushStore.js b/src/puter-js/src/modules/notifications/lib/pushStore.js index d514c71a4..3e6f4d3a1 100644 --- a/src/puter-js/src/modules/notifications/lib/pushStore.js +++ b/src/puter-js/src/modules/notifications/lib/pushStore.js @@ -1,26 +1,16 @@ -// IndexedDB shared with `push-sw.js` on the same origin; names must match it. -export const PUSH_DB_NAME = 'puter-push'; -export const HANDLERS_STORE = 'handlers'; -export const CLICKS_STORE = 'clicks'; +import { + CLICKS_STORE, + HANDLERS_STORE, + OPT_IN_PREFIX, + PUSH_DB_NAME, + SUBSCRIPTION_CHANGED_PREFIX, + SYNCED_PREFIX, +} from './pushNames.js'; + +export * from './pushNames.js'; -// Kept in the handlers store under keys no channel can take, so the database -// stays at the version workers already installed open. -const OPT_IN_PREFIX = 'puter:opt-in:'; -export const SERVER_KEY_ENTRY = 'puter:server-key'; -/** Every key the server named as Puter's, the current one first. */ -export const SERVER_KEYS_ENTRY = 'puter:server-keys'; -/** Per user: `{ endpoint, at }` of the subscription the server last confirmed. */ -export const SYNCED_PREFIX = 'puter:synced:'; -/** Per worker scope: set by `push-sw.js` when a subscription is replaced. */ -export const SUBSCRIPTION_CHANGED_PREFIX = 'puter:subscription-changed:'; -/** Per worker scope: `{ endpoint, receipt }` the server last gave. */ -export const RECEIPT_PREFIX = 'puter:receipt:'; -/** Where a tap without a URL goes, per worker scope; read by `push-sw.js`. */ -export const TAP_BASE_PREFIX = 'puter:tap-base:'; /** How long a kept tap waits for its page, as in `push-sw.js`. */ export const CLICK_KEEP_MS = 5 * 60 * 1000; -/** What a worker posts when the browser replaced the push subscription. */ -export const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; const open = (idb) => new Promise((resolve, reject) => { diff --git a/src/puter-js/src/modules/notifications/webPush.test.js b/src/puter-js/src/modules/notifications/webPush.test.js index 6d2ebbbbc..31d561b75 100644 --- a/src/puter-js/src/modules/notifications/webPush.test.js +++ b/src/puter-js/src/modules/notifications/webPush.test.js @@ -2469,6 +2469,88 @@ describe('enable after the user removed this browser in Puter', () => { }); }); +describe('the push record inside the Puter GUI', () => { + const SYNCED = 'handlers:puter:synced:u-1'; + const CHANGED = `handlers:puter:subscription-changed:${ORIGIN}/`; + const RECEIPT = `handlers:puter:receipt:${ORIGIN}/`; + const guiNav = (existing = null) => { + const nav = makeNav({ + existing, + active: { scriptURL: `${ORIGIN}/sw.js` }, + }); + withBrowser(nav); + return nav; + }; + + it('records the endpoint the server confirmed and clears the mark on enable()', async () => { + guiNav(makeSubscription()); + server(); + store.set(CHANGED, { at: 1, oldEndpoint: 'https://push.example/0' }); + const { module } = makeModule({ env: 'gui' }); + await expect(module._webPushRecord()).resolves.toEqual({ + endpoint: null, + changed: { at: 1, oldEndpoint: 'https://push.example/0' }, + }); + await expect(module.enable({ background: true })).resolves.toBe(true); + expect(store.get(SYNCED)).toEqual({ + endpoint: 'https://push.example/send/abc', + at: expect.any(Number), + }); + expect(store.has(CHANGED)).toBe(false); + await expect(module._webPushRecord()).resolves.toEqual({ + endpoint: 'https://push.example/send/abc', + changed: null, + }); + }); + + it('records a confirmed endpoint without clearing the mark', async () => { + guiNav(); + store.set(CHANGED, { at: 1 }); + const { module } = makeModule({ env: 'gui' }); + await expect( + module._noteWebPushSynced('https://push.example/1'), + ).resolves.toBe(true); + await expect(module._webPushRecord()).resolves.toEqual({ + endpoint: 'https://push.example/1', + changed: { at: 1 }, + }); + await expect( + module._webPushRecord({ endpoint: false }), + ).resolves.toEqual({ endpoint: null, changed: { at: 1 } }); + }); + + it('reads nulls, and records nothing, when IndexedDB fails', async () => { + guiNav(); + storage.broken = true; + const { module } = makeModule({ env: 'gui' }); + await expect(module._webPushRecord()).resolves.toEqual({ + endpoint: null, + changed: null, + }); + await expect( + module._noteWebPushSynced('https://push.example/1'), + ).resolves.toBe(false); + }); + + it('ends a removed subscription and forgets its receipt and the mark', async () => { + const removed = makeSubscription(undefined, 'https://push.example/1'); + guiNav(removed); + store.set(CHANGED, { at: 1, oldEndpoint: 'https://push.example/0' }); + store.set(RECEIPT, { + endpoint: 'https://push.example/1', + receipt: 'r', + }); + store.set(SYNCED, { endpoint: 'https://push.example/0', at: 1 }); + const { module } = makeModule({ env: 'gui' }); + await module._dropRemovedWebPush(); + expect(removed.unsubscribe).toHaveBeenCalledTimes(1); + expect(store.has(RECEIPT)).toBe(false); + expect(store.has(CHANGED)).toBe(false); + expect(store.get(SYNCED)?.endpoint).toBe('https://push.example/0'); + expect(mockRequest).not.toHaveBeenCalled(); + }); +}); + describe('status', () => { it('is unavailable where the browser has no Web Push, and outside a page', async () => { const { module } = makeModule(); diff --git a/src/puter-js/src/push-sw.js b/src/puter-js/src/push-sw.js index e4c0f0623..27775e126 100644 --- a/src/puter-js/src/push-sw.js +++ b/src/puter-js/src/push-sw.js @@ -20,22 +20,28 @@ (() => { if (self.puterPush) return; - // Shared with puter.js on the same origin (modules/notifications/lib/pushStore.js). - const DB_NAME = 'puter-push'; - const HANDLERS = 'handlers'; - const CLICKS = 'clicks'; + // Shared with puter.js: generated from lib/pushNames.js by tools/pushWorkerNames.mjs. + const CLICKS_STORE = 'clicks'; + const HANDLERS_STORE = 'handlers'; + const OPT_IN_PREFIX = 'puter:opt-in:'; + const PUSH_DB_NAME = 'puter-push'; + const RECEIPT_PREFIX = 'puter:receipt:'; + const SERVER_KEYS_ENTRY = 'puter:server-keys'; + const SERVER_KEY_ENTRY = 'puter:server-key'; + const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; + const SUBSCRIPTION_CHANGED_PREFIX = 'puter:subscription-changed:'; + const SYNCED_PREFIX = 'puter:synced:'; + const TAP_BASE_PREFIX = 'puter:tap-base:'; + // End of generated names. const HANDLER_TIMEOUT_MS = 5000; const CLICK_KEEP_MS = 5 * 60 * 1000; const CLICK_ACK_BUDGET_MS = 600; // Firefox allows openWindow for 1 s after the click; this leaves room for it. const CLICK_OPEN_BUDGET_MS = 800; - // Saved by the page; the worker's scope is used when there is none. - const TAP_BASE_PREFIX = 'puter:tap-base:'; const DEFAULT_TITLE = 'New notification'; const CHALLENGE_MESSAGE = 'puter-push-challenge'; const CLICK_MESSAGE = 'puter-notification-click'; const CLICK_ACK_MESSAGE = 'puter-notification-click-ack'; - const CHANGED_MESSAGE = 'puter-push-subscription-changed'; const CLICK_PARAM = 'puter.notification'; const SHOWN_FIELDS = ['title', 'body', 'icon', 'badge', 'image', 'tag', 'url']; @@ -45,10 +51,10 @@ let nextClickId = 0; const openDB = () => new Promise((resolve, reject) => { - const req = indexedDB.open(DB_NAME, 1); + const req = indexedDB.open(PUSH_DB_NAME, 1); req.onupgradeneeded = () => { - req.result.createObjectStore(HANDLERS); - req.result.createObjectStore(CLICKS); + req.result.createObjectStore(HANDLERS_STORE); + req.result.createObjectStore(CLICKS_STORE); }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); @@ -119,7 +125,7 @@ if ( ! channel ) return null; if ( registered.has(channel) ) return registered.get(channel); if ( ! useSavedHandlers ) return null; - const source = await idb(HANDLERS, 'readonly', (s) => s.get(channel)); + const source = await idb(HANDLERS_STORE, 'readonly', (s) => s.get(channel)); if ( typeof source !== 'string' ) return null; const fn = new Function(`"use strict"; return (${source});`)(); return typeof fn === 'function' ? fn : null; @@ -173,7 +179,7 @@ async function tapBase () { const scope = self.registration.scope ?? `${self.location.origin}/`; try { - const base = await idb(HANDLERS, 'readonly', (s) => s.get(TAP_BASE_PREFIX + scope)); + const base = await idb(HANDLERS_STORE, 'readonly', (s) => s.get(TAP_BASE_PREFIX + scope)); if ( typeof base === 'string' && new URL(base).origin === self.location.origin ) return base; } catch { // nothing saved, or IndexedDB is unavailable @@ -239,7 +245,7 @@ async function forgetOldClicks () { const cutoff = Date.now() - CLICK_KEEP_MS; - await idb(CLICKS, 'readwrite', (s) => { + await idb(CLICKS_STORE, 'readwrite', (s) => { const req = s.openCursor(); req.addEventListener('success', () => { const cursor = req.result; @@ -254,7 +260,7 @@ // One readwrite get+delete, so only the page or the worker gets the tap. async function claimClick (uid, id) { const matches = (kept) => !!kept && (id === undefined || kept.id === id); - const kept = await idb(CLICKS, 'readwrite', (s) => { + const kept = await idb(CLICKS_STORE, 'readwrite', (s) => { const req = s.get(uid); req.addEventListener('success', () => { if ( matches(req.result) ) s.delete(uid); @@ -266,7 +272,7 @@ // Like claimClick, but keeps the copy, without its id, for the page opened next. async function reclaimClick (uid, id) { - const kept = await idb(CLICKS, 'readwrite', (s) => { + const kept = await idb(CLICKS_STORE, 'readwrite', (s) => { const req = s.get(uid); req.addEventListener('success', () => { if ( req.result?.id !== id ) return; @@ -296,7 +302,7 @@ async function keepClick (click, id) { if ( ! click.uid ) return false; try { - await idb(CLICKS, 'readwrite', (s) => s.put({ ...click, at: Date.now(), ...(id ? { id } : {}) }, click.uid)); + await idb(CLICKS_STORE, 'readwrite', (s) => s.put({ ...click, at: Date.now(), ...(id ? { id } : {}) }, click.uid)); return true; } catch ( err ) { console.warn('[puter] could not keep a tap', err); @@ -372,12 +378,6 @@ event.waitUntil(Promise.all([routeClick(puter, event.action, startedAt), forgetOldClicksQuietly()])); }); - // Entries pushStore.js writes. - const OPT_IN_PREFIX = 'puter:opt-in:'; - const SERVER_KEY = 'puter:server-key'; - const SERVER_KEYS = 'puter:server-keys'; - const CHANGED_PREFIX = 'puter:subscription-changed:'; - const fromBase64Url = (value) => { const padded = value.replace(/-/g, '+').replace(/_/g, '/'); const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4)); @@ -396,23 +396,23 @@ } async function puterKeys () { - const last = await idb(HANDLERS, 'readonly', (s) => s.get(SERVER_KEY)); - const listed = await idb(HANDLERS, 'readonly', (s) => s.get(SERVER_KEYS)); + const last = await idb(HANDLERS_STORE, 'readonly', (s) => s.get(SERVER_KEY_ENTRY)); + const listed = await idb(HANDLERS_STORE, 'readonly', (s) => s.get(SERVER_KEYS_ENTRY)); return [last, ...(Array.isArray(listed) ? listed : [])].filter((key) => str(key)); } // No Puter session here: keep Puter's subscription and mark it for the next page load to register. async function keepSubscription (event) { - const optIns = await idb(HANDLERS, 'readonly', (s) => s.count(IDBKeyRange.bound(OPT_IN_PREFIX, `${OPT_IN_PREFIX}\uffff`))); + const optIns = await idb(HANDLERS_STORE, 'readonly', (s) => s.count(IDBKeyRange.bound(OPT_IN_PREFIX, `${OPT_IN_PREFIX}\uffff`))); if ( ! optIns ) return; const keys = await puterKeys(); const old = event.oldSubscription?.options?.applicationServerKey; if ( old && ! keys.some((key) => sameKey(old, key)) ) return; - await idb(HANDLERS, 'readwrite', (s) => s.put(Date.now(), CHANGED_PREFIX + self.registration.scope)); + await idb(HANDLERS_STORE, 'readwrite', (s) => s.put(Date.now(), SUBSCRIPTION_CHANGED_PREFIX + self.registration.scope)); if ( event.newSubscription || ! keys.length ) return; if ( await self.registration.pushManager.getSubscription() ) return; // Without the old subscription, only a worker a Puter page used (it saved a tap base) subscribes. - if ( ! old && ! await idb(HANDLERS, 'readonly', (s) => s.get(TAP_BASE_PREFIX + self.registration.scope)) ) return; + if ( ! old && ! await idb(HANDLERS_STORE, 'readonly', (s) => s.get(TAP_BASE_PREFIX + self.registration.scope)) ) return; await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: fromBase64Url(keys[0]) }); } @@ -423,7 +423,7 @@ } catch ( err ) { console.warn('[puter] could not keep the push subscription', err); } - for ( const win of await windows() ) win.postMessage({ type: CHANGED_MESSAGE }); + for ( const win of await windows() ) win.postMessage({ type: SUBSCRIPTION_CHANGED_MESSAGE }); })()); }); diff --git a/src/puter-js/webpack.config.js b/src/puter-js/webpack.config.js index b422b521a..cf33b3681 100644 --- a/src/puter-js/webpack.config.js +++ b/src/puter-js/webpack.config.js @@ -1,6 +1,7 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; import webpack from 'webpack'; +import { hasPushNames } from '../../tools/pushNamesBlock.mjs'; // '__dirname' isn't defined by default in ES modules. // We didn't really want to migrate this file to ESM because @@ -20,8 +21,12 @@ class EmitPushWorker { compilation.hooks.processAssets.tap( { name: 'EmitPushWorker', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, () => { + const source = readFileSync(PUSH_WORKER, 'utf8'); + if ( ! hasPushNames(source) ) { + compilation.errors.push(new webpack.WebpackError('push-sw.js: stale push names; run node tools/pushWorkerNames.mjs')); + } // `minimized` keeps terser off it, so the published file is the source. - compilation.emitAsset('push-sw.js', new webpack.sources.RawSource(readFileSync(PUSH_WORKER, 'utf8')), { minimized: true }); + compilation.emitAsset('push-sw.js', new webpack.sources.RawSource(source), { minimized: true }); }, ); }); diff --git a/tools/pushNamesBlock.mjs b/tools/pushNamesBlock.mjs new file mode 100644 index 000000000..c3348e3b0 --- /dev/null +++ b/tools/pushNamesBlock.mjs @@ -0,0 +1,29 @@ +import * as names from '../src/puter-js/src/modules/notifications/lib/pushNames.js'; + +const START = + '// Shared with puter.js: generated from lib/pushNames.js by tools/pushWorkerNames.mjs.'; +const END = '// End of generated names.'; + +/** `source` with its generated names block rewritten from `pushNames.js`. */ +export const withPushNames = (source) => { + const eol = source.includes('\r\n') ? '\r\n' : '\n'; + const text = source.replace(/\r\n/g, '\n'); + const start = text.indexOf(START); + const end = text.indexOf(END, start); + if (start < 0 || end < 0) throw new Error('no generated names block'); + const indent = text.slice(text.lastIndexOf('\n', start) + 1, start); + const lines = Object.keys(names) + .sort() + .map((name) => `${indent}const ${name} = '${names[name]}';`); + const next = `${text.slice(0, start)}${START}\n${lines.join('\n')}\n${indent}${text.slice(end)}`; + return eol === '\n' ? next : next.replace(/\n/g, eol); +}; + +/** Whether `source`'s generated names match `pushNames.js`. */ +export const hasPushNames = (source) => { + try { + return withPushNames(source) === source; + } catch { + return false; + } +}; diff --git a/tools/pushWorkerNames.mjs b/tools/pushWorkerNames.mjs new file mode 100644 index 000000000..a659fc422 --- /dev/null +++ b/tools/pushWorkerNames.mjs @@ -0,0 +1,18 @@ +// Rewrites both push workers' names block from pushNames.js; --check only reports. + +import { readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { withPushNames } from './pushNamesBlock.mjs'; + +const check = process.argv.includes('--check'); +let stale = false; +for (const file of ['src/puter-js/src/push-sw.js', 'src/gui/src/sw.js']) { + const at = fileURLToPath(new URL(`../${file}`, import.meta.url)); + const source = readFileSync(at, 'utf8'); + const next = withPushNames(source); + if (next === source) continue; + stale = true; + if (check) console.error(`stale push names: ${file}`); + else writeFileSync(at, next); +} +if (check && stale) process.exit(1);