diff --git a/doc/push-client.md b/doc/push-client.md index 684cb1236..b5d9250dc 100644 --- a/doc/push-client.md +++ b/doc/push-client.md @@ -59,9 +59,9 @@ Apps on their own origin do the same through `push-sw.js`, which they import int ```ts interface PushClient { - enable(): Promise<{ deviceUid: string }>; + enable(options?: { background?: boolean }): Promise<{ deviceUid: string }>; disable(): Promise; - status(): Promise<{ + status(options?: { cached?: boolean }): Promise<{ permission: 'default' | 'granted' | 'denied'; registered: boolean; deviceUid?: string; @@ -69,12 +69,12 @@ 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 holds `notifications:push`; the browser does not prompt then. 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'`). It then resolves the `uid` of this browser's `webpush` device from `listDevices()`. 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 holds `notifications:push`; 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. 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 the same registration without replacing a removed subscription or opening Puter's sign-in. It 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 `deviceUid` is that device's `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 `deviceUid` is that device's `uid`. 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, starting from `enable()` or a read, and drops it on `disable()`, a failed `enable()`, an unregistered answer, and the worker's `puter-push-subscription-changed` message, so a new page load always asks the server. 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:` in `localStorage`, written by Turn off and by Remove on this browser's device, and cleared when `enable()` resolves. The silent registration above skips a browser with that record, so a device removed here stays removed while one removed from another device, or a new sign-in in a browser that already allows notifications, registers again. +Core keeps its own record of a browser the user turned off, `puter.push.browser-off:` 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. diff --git a/src/gui/src/helpers/pushClient.js b/src/gui/src/helpers/pushClient.js index adaa098e0..4dae670bc 100644 --- a/src/gui/src/helpers/pushClient.js +++ b/src/gui/src/helpers/pushClient.js @@ -21,7 +21,7 @@ /** @typedef {{ permission: 'default'|'granted'|'denied', registered: boolean, deviceUid?: string }} PushClientStatus */ -/** @typedef {{ enable: () => Promise<{ deviceUid: string }>, disable: () => Promise, status: () => Promise }} PushClient */ +/** `background`: a call without a click, which leaves a browser removed in Puter removed (`push_device_removed`). `cached`: a page may answer with its last `on`. @typedef {{ enable: (options?: { background?: boolean }) => Promise<{ deviceUid: string }>, disable: () => Promise, status: (options?: { cached?: boolean }) => Promise }} PushClient */ /** @typedef {'checking'|'unavailable'|'blocked'|'on'|'off'} BrowserPushState */ @@ -79,11 +79,11 @@ export const pushClientWithin = (ms = PUSH_CLIENT_WAIT_MS, params = globalThis.g globalThis.addEventListener(PUSH_CLIENT_REGISTERED_EVENT, done); }); -/** @param {PushClient|null} client @returns {Promise} */ -export const browserPushState = async (client) => { +/** With `cached`, an `on` this page already read may answer. @param {PushClient|null} client @param {{ cached?: boolean }} [options] @returns {Promise} */ +export const browserPushState = async (client, { cached = false } = {}) => { if ( ! client ) return 'unavailable'; try { - const status = await client.status(); + const status = await client.status({ cached }); if ( status?.permission === 'denied' ) return 'blocked'; return status?.registered ? 'on' : 'off'; } catch ( e ) { diff --git a/src/gui/src/helpers/pushSync.js b/src/gui/src/helpers/pushSync.js index b6199b7a5..7479a8fe9 100644 --- a/src/gui/src/helpers/pushSync.js +++ b/src/gui/src/helpers/pushSync.js @@ -24,17 +24,17 @@ import { listPushApps } from './notificationApi.js'; import { browserPushOptedOut, browserPushState, - enableBrowserPush, PUSH_PERMISSION, pushClientWithin, + setBrowserPushOptOut, } from './pushClient.js'; -/** @typedef {'skipped'|'opted_out'|'unavailable'|'blocked'|'on'|'off'|'no_app'|'failed'} PushSyncResult */ +/** @typedef {'skipped'|'opted_out'|'unavailable'|'blocked'|'on'|'off'|'no_app'|'removed'|'failed'} PushSyncResult */ /** @type {Promise|null} */ let inFlight = null; -/** Turns push on here when the browser already grants it, the user has not turned it off here, and an app holds `notifications:push` for Puter's devices: the one named by `appUid`, or any app without one. One run at a time; a call during a run joins it. @param {{ appUid?: string }} [scope] @param {{ NotificationApi?: { permission: string }, userUid?: string, storage?: Storage, holdsPush?: () => Promise }} [deps] @returns {Promise} */ +/** Turns push on here when the browser already grants it, the user has not turned it off here, and an app holds `notifications:push` for Puter's devices: the one named by `appUid`, or any app without one. A browser the user removed in Puter is left off, as if turned off here. An `on` this page already read counts. One run at a time; a call during a run joins it. @param {{ appUid?: string }} [scope] @param {{ NotificationApi?: { permission: string }, userUid?: string, storage?: Storage, holdsPush?: () => Promise }} [deps] @returns {Promise} */ export const syncBrowserPush = (scope, deps) => { if ( inFlight ) return inFlight; inFlight = runSync(scope, deps).finally(() => { @@ -58,7 +58,7 @@ const runSync = async ({ appUid } = {}, { if ( NotificationApi?.permission !== 'granted' || ! userUid ) return 'skipped'; if ( browserPushOptedOut(userUid, storage) ) return 'opted_out'; const client = await pushClientWithin(); - const state = await browserPushState(client); + const state = await browserPushState(client, { cached: true }); if ( state !== 'off' ) return state; try { if ( ! await holdsPush() ) return 'no_app'; @@ -66,5 +66,15 @@ const runSync = async ({ appUid } = {}, { console.warn('[push] could not tell whether an app may send pushes', e); return 'failed'; } - return await enableBrowserPush(client, userUid) ? 'on' : 'failed'; + try { + await client.enable({ background: true }); + } catch ( e ) { + if ( e?.code === 'push_device_removed' ) { + setBrowserPushOptOut(userUid, true, storage); + return 'removed'; + } + console.debug('[push] enable failed', e); + return 'failed'; + } + return 'on'; }; diff --git a/src/gui/src/helpers/pushSync.test.js b/src/gui/src/helpers/pushSync.test.js index 44c6efadf..65ca745be 100644 --- a/src/gui/src/helpers/pushSync.test.js +++ b/src/gui/src/helpers/pushSync.test.js @@ -58,12 +58,68 @@ const off = () => { return client; }; +describe('syncBrowserPush with the built-in client', () => { + const current = { uid: 'dev-1', platform: 'webpush', current: true }; + const builtIn = async () => { + const { webPushClient } = await import('./webPushClient.js'); + const notifications = { + enable: vi.fn(async () => true), + _enableWebPush: vi.fn(async () => {}), + disable: vi.fn(async () => true), + listDevices: vi.fn(async () => [current]), + }; + const nav = { + serviceWorker: { + getRegistration: async () => ({ pushManager: { getSubscription: async () => ({ endpoint: 'https://push.test/1' }) } }), + addEventListener: () => {}, + }, + }; + registerPushClient(webPushClient({ notifications, NotificationApi: granted, nav, userUid: () => 'u-1' })); + return notifications; + }; + + it('lists devices on the first launch only, once push is on', async () => { + const notifications = await builtIn(); + const deps = { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true }; + await expect(syncBrowserPush({ appUid: 'app-1' }, deps)).resolves.toBe('on'); + await expect(syncBrowserPush({ appUid: 'app-2' }, deps)).resolves.toBe('on'); + expect(notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it('does not subscribe again, and stays off, when the user removed this browser in Puter', async () => { + const notifications = await builtIn(); + notifications.listDevices.mockResolvedValue([]); + notifications._enableWebPush.mockRejectedValue(Object.assign(new Error('removed'), { code: 'push_device_removed' })); + const deps = { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true }; + await expect(syncBrowserPush({}, deps)).resolves.toBe('removed'); + expect(notifications._enableWebPush).toHaveBeenCalledWith({ url: '/sw.js', scope: '/' }, { background: true }); + expect(notifications.enable).not.toHaveBeenCalled(); + await expect(syncBrowserPush({}, deps)).resolves.toBe('opted_out'); + expect(notifications._enableWebPush).toHaveBeenCalledTimes(1); + }); +}); + describe('syncBrowserPush', () => { it('registers this browser again when an app may send pushes', async () => { const client = off(); const holdsPush = vi.fn(async () => true); await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush })).resolves.toBe('on'); expect(client.enable).toHaveBeenCalledTimes(1); + expect(client.enable).toHaveBeenCalledWith({ background: true }); + }); + + it('leaves a browser the user removed in Puter off, now and on later loads', async () => { + const client = off(); + client.enable.mockRejectedValue(Object.assign(new Error('removed'), { code: 'push_device_removed' })); + const deps = { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true }; + await expect(syncBrowserPush({}, deps)).resolves.toBe('removed'); + expect(localStorage.getItem('puter.push.browser-off:u-1')).toBe('1'); + + client.enable.mockClear(); + client.status.mockClear(); + await expect(syncBrowserPush({ appUid: 'app-1' }, deps)).resolves.toBe('opted_out'); + expect(client.status).not.toHaveBeenCalled(); + expect(client.enable).not.toHaveBeenCalled(); }); it('runs once at a time: a call during a run joins it', async () => { diff --git a/src/gui/src/helpers/webPushClient.js b/src/gui/src/helpers/webPushClient.js index bf4f54c34..d3365fe8a 100644 --- a/src/gui/src/helpers/webPushClient.js +++ b/src/gui/src/helpers/webPushClient.js @@ -19,33 +19,95 @@ // Puter's own push client: standard Web Push through `/sw.js` via `puter.notifications`, used when the server publishes `pushWebPushKey`. +/** The GUI's worker, as `puter.notifications` registers it. */ +const GUI_WORKER = { url: '/sw.js', scope: '/' }; + +/** What `/sw.js` posts when the browser replaced the subscription. */ +const SUBSCRIPTION_CHANGED_MESSAGE = 'puter-push-subscription-changed'; + +/** How long a page answers `cached` reads from its last `on`. */ +export const ON_KEPT_MS = 5 * 60 * 1000; + /** @returns {import('./pushClient.js').PushClient} */ export const webPushClient = ({ notifications = globalThis.puter?.notifications, NotificationApi = globalThis.Notification, nav = globalThis.navigator, + userUid = () => globalThis.user?.uuid, + now = Date.now, } = {}) => { + // The last `on` this page read; a new page always asks the server. + /** @type {{ userUid: string, endpoint: string, deviceUid: string, at: number }|null} */ + let lastOn = null; + let generation = 0; + const forgetOn = () => { + lastOn = null; + generation++; + }; + nav?.serviceWorker?.addEventListener?.('message', (event) => { + if ( event.data?.type === SUBSCRIPTION_CHANGED_MESSAGE ) forgetOn(); + }); + const currentDevice = async () => { const devices = await notifications.listDevices(); return devices.find((d) => d.current && d.platform === 'webpush') ?? null; }; + const subscriptionHere = async () => { + const registration = await nav.serviceWorker?.getRegistration('/'); + return await registration?.pushManager?.getSubscription() ?? null; + }; return { // Not async before `enable()`: it asks the browser inside the click. - enable: () => notifications.enable().then(async (on) => { - if ( ! on ) throw new Error(`notifications ${NotificationApi?.permission ?? 'unavailable'}`); - const device = await currentDevice(); - if ( ! device ) throw new Error('this browser was not registered'); - return { deviceUid: device.uid }; - }), - disable: async () => { - await notifications.disable(); + enable: ({ background = false } = {}) => { + forgetOn(); + const turningOn = background + ? notifications._enableWebPush(GUI_WORKER, { background: true }).then(() => true) + : notifications.enable(); + return turningOn.then(async (on) => { + if ( ! on ) throw new Error(`notifications ${NotificationApi?.permission ?? 'unavailable'}`); + const reading = generation; + const user = userUid(); + const [device, subscription] = await Promise.all([currentDevice(), subscriptionHere()]); + if ( ! device ) throw new Error('this browser was not registered'); + if ( reading === generation && user && user === userUid() && subscription ) { + lastOn = { userUid: user, endpoint: subscription.endpoint, deviceUid: device.uid, at: now() }; + } + return { deviceUid: device.uid }; + }).catch((e) => { + // A read begun meanwhile keeps nothing from before the failure. + forgetOn(); + throw e; + }); }, - status: async () => { + disable: async () => { + forgetOn(); + try { + await notifications.disable(); + } finally { + forgetOn(); + } + }, + status: async ({ cached = false } = {}) => { const permission = NotificationApi?.permission ?? 'default'; - const registration = await nav.serviceWorker?.getRegistration('/'); - const subscription = await registration?.pushManager?.getSubscription(); - if ( permission !== 'granted' || ! subscription ) return { permission, registered: false }; + const subscription = await subscriptionHere(); + if ( permission !== 'granted' || ! subscription ) { + forgetOn(); + return { permission, registered: false }; + } + const user = userUid(); + const kept = lastOn && lastOn.userUid === user && lastOn.endpoint === subscription.endpoint + && now() - lastOn.at < ON_KEPT_MS; + if ( cached && kept ) { + return { permission, registered: true, deviceUid: lastOn.deviceUid }; + } + const reading = generation; const device = await currentDevice(); + if ( reading === generation ) { + // Devices listed for another user who signed in meanwhile aren't kept. + lastOn = device && user && user === userUid() + ? { userUid: user, endpoint: subscription.endpoint, deviceUid: device.uid, at: now() } + : null; + } return device ? { permission, registered: true, deviceUid: device.uid } : { permission, registered: false }; diff --git a/src/gui/src/helpers/webPushClient.test.js b/src/gui/src/helpers/webPushClient.test.js index 6d15512b4..129f88898 100644 --- a/src/gui/src/helpers/webPushClient.test.js +++ b/src/gui/src/helpers/webPushClient.test.js @@ -18,20 +18,28 @@ */ import { describe, expect, it, vi } from 'vitest'; -import { webPushClient } from './webPushClient.js'; +import { ON_KEPT_MS, webPushClient } from './webPushClient.js'; -const make = ({ on = true, devices = [], permission = 'granted', subscription = {} } = {}) => { +const make = ({ on = true, devices = [], permission = 'granted', subscription = { endpoint: 'https://push.test/1' }, user = 'u-1' } = {}) => { const notifications = { enable: vi.fn(async () => on), + _enableWebPush: vi.fn(async () => {}), disable: vi.fn(async () => true), listDevices: vi.fn(async () => devices), }; + const listeners = new Set(); + const state = { subscription, user, now: 0 }; const nav = { serviceWorker: { - getRegistration: vi.fn(async () => ({ pushManager: { getSubscription: async () => subscription } })), + getRegistration: vi.fn(async () => ({ pushManager: { getSubscription: async () => state.subscription } })), + addEventListener: (type, fn) => listeners.add(fn), }, }; - return { notifications, client: webPushClient({ notifications, NotificationApi: { permission }, nav }) }; + const post = (data) => { + for ( const fn of listeners ) fn({ data }); + }; + const client = webPushClient({ notifications, NotificationApi: { permission }, nav, userUid: () => state.user, now: () => state.now }); + return { notifications, client, post, state }; }; const current = { uid: 'd1', platform: 'webpush', current: true }; @@ -61,4 +69,161 @@ describe('webPushClient', () => { await client.disable(); expect(notifications.disable).toHaveBeenCalled(); }); + + it('turns on from a click through enable(), which replaces a browser removed in Puter', async () => { + const { notifications, client } = make({ devices: [current] }); + await client.enable(); + expect(notifications.enable).toHaveBeenCalledTimes(1); + expect(notifications._enableWebPush).not.toHaveBeenCalled(); + }); + + it('turns on in the background without replacing a browser removed in Puter', async () => { + const { notifications, client } = make({ devices: [current] }); + await expect(client.enable({ background: true })).resolves.toEqual({ deviceUid: 'd1' }); + expect(notifications._enableWebPush).toHaveBeenCalledWith({ url: '/sw.js', scope: '/' }, { background: true }); + expect(notifications.enable).not.toHaveBeenCalled(); + + const removed = Object.assign(new Error('removed'), { code: 'push_device_removed' }); + notifications._enableWebPush.mockRejectedValue(removed); + await expect(client.enable({ background: true })).rejects.toBe(removed); + }); +}); + +describe('webPushClient status with cached', () => { + const on = { permission: 'granted', registered: true, deviceUid: 'd1' }; + + /** A client whose last read was `on`. */ + const readOn = async () => { + const made = make({ devices: [current] }); + await expect(made.client.status()).resolves.toEqual(on); + made.notifications.listDevices.mockClear(); + return made; + }; + + it('answers with the last on this page read, without listing devices', async () => { + const { notifications, client } = await readOn(); + await expect(client.status({ cached: true })).resolves.toEqual(on); + expect(notifications.listDevices).not.toHaveBeenCalled(); + }); + + it('lists devices for a read without cached', async () => { + const { notifications, client } = await readOn(); + await client.status(); + expect(notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it('lists devices when nothing was read yet', async () => { + const { notifications, client } = make({ devices: [current] }); + await expect(client.status({ cached: true })).resolves.toEqual(on); + expect(notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['the worker says the subscription changed', ({ post }) => post({ type: 'puter-push-subscription-changed' })], + ['the subscription has another endpoint', ({ state }) => { + state.subscription = { endpoint: 'https://push.test/2' }; + }], + ['another user signed in', ({ state }) => { + state.user = 'u-2'; + }], + ['the user signed out', ({ state }) => { + state.user = undefined; + }], + ['the last on is older than a page keeps it', ({ state }) => { + state.now += ON_KEPT_MS; + }], + ['enable() failed', async ({ client, notifications }) => { + notifications.enable.mockResolvedValueOnce(false); + await client.enable().catch(() => {}); + }], + ['disable() ran', async ({ client }) => { + await client.disable(); + }], + ['a read found this browser unregistered', async ({ client, notifications }) => { + notifications.listDevices.mockResolvedValueOnce([]); + await client.status(); + }], + ])('asks the server again once %s', async (_label, change) => { + const made = await readOn(); + await change(made); + made.notifications.listDevices.mockClear(); + await made.client.status({ cached: true }); + expect(made.notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it('answers with the on enable() read, without listing devices again', async () => { + const { notifications, client } = make({ devices: [current] }); + await client.enable({ background: true }); + notifications.listDevices.mockClear(); + await expect(client.status({ cached: true })).resolves.toEqual(on); + expect(notifications.listDevices).not.toHaveBeenCalled(); + }); + + it('keeps answering with the last on until it is too old', async () => { + const { notifications, client, state } = await readOn(); + state.now += ON_KEPT_MS - 1; + await expect(client.status({ cached: true })).resolves.toEqual(on); + expect(notifications.listDevices).not.toHaveBeenCalled(); + }); + + it('reports off after disable()', async () => { + const { notifications, client } = await readOn(); + await client.disable(); + notifications.listDevices.mockResolvedValue([]); + await expect(client.status({ cached: true })).resolves.toEqual({ permission: 'granted', registered: false }); + }); + + it('keeps no on read before a disable() that ended first', async () => { + const { notifications, client } = make({ devices: [current] }); + let list; + notifications.listDevices.mockImplementationOnce(() => new Promise((resolve) => { + list = resolve; + })); + const reading = client.status(); + await vi.waitFor(() => expect(list).toBeDefined()); + await client.disable(); + list([current]); + await reading; + notifications.listDevices.mockResolvedValue([]); + await expect(client.status({ cached: true })).resolves.toEqual({ permission: 'granted', registered: false }); + }); + + it('keeps no on from a device list that another user`s sign-in overlapped', async () => { + const { notifications, client, state } = make({ devices: [current] }); + let list; + notifications.listDevices.mockImplementationOnce(() => new Promise((resolve) => { + list = resolve; + })); + const reading = client.status(); + await vi.waitFor(() => expect(list).toBeDefined()); + state.user = 'u-2'; + list([current]); + await reading; + state.user = 'u-1'; + notifications.listDevices.mockClear(); + await client.status({ cached: true }); + expect(notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it('keeps no on read while an enable() that failed was running', async () => { + const { notifications, client } = make({ devices: [current] }); + let fail; + notifications._enableWebPush.mockImplementationOnce(() => new Promise((_, reject) => { + fail = reject; + })); + const enabling = client.enable({ background: true }); + await expect(client.status()).resolves.toEqual(on); + fail(new Error('no push service')); + await expect(enabling).rejects.toThrow('no push service'); + notifications.listDevices.mockClear(); + await client.status({ cached: true }); + expect(notifications.listDevices).toHaveBeenCalledTimes(1); + }); + + it('is off without listing devices once the browser has no subscription or permission', async () => { + const { notifications, client, state } = await readOn(); + state.subscription = null; + await expect(client.status({ cached: true })).resolves.toEqual({ permission: 'granted', registered: false }); + expect(notifications.listDevices).not.toHaveBeenCalled(); + }); }); diff --git a/src/gui/src/services/AppPushService.js b/src/gui/src/services/AppPushService.js index b6a6b10b2..0addcd060 100644 --- a/src/gui/src/services/AppPushService.js +++ b/src/gui/src/services/AppPushService.js @@ -46,12 +46,13 @@ export class AppPushService extends Service { /** * IPC: this browser's push state for the calling app, `on` only while - * push is on here and the app holds `notifications:push`. + * push is on here and the app holds `notifications:push`. An `on` this + * page already read for the browser counts. * * @returns {Promise<{ state: 'on'|'off'|'blocked'|'unavailable' }>} */ async pushStatus (_params, { ipc_context } = {}) { - const state = await browserPushState(await pushClientWithin()); + const state = await browserPushState(await pushClientWithin(), { cached: true }); if ( state !== 'on' ) return { state }; const held = await appHoldsPermissions([PUSH_PERMISSION], app_uid_of(ipc_context)); return { state: held ? 'on' : 'off' }; diff --git a/src/gui/src/services/AppPushService.test.js b/src/gui/src/services/AppPushService.test.js index 3de0fbbdf..9121180c4 100644 --- a/src/gui/src/services/AppPushService.test.js +++ b/src/gui/src/services/AppPushService.test.js @@ -58,9 +58,11 @@ beforeEach(() => { registerPushClient({ enable: async () => ({ deviceUid: 'd-1' }), disable: async () => {}, - status: async () => { + status: async (options) => { + browser.asked = options; if ( browser.broken ) throw new Error('no push service'); - return { ...browser }; + const { asked: _, ...status } = browser; + return status; }, }); globalThis.fetch = vi.fn(async (url, init) => { @@ -83,6 +85,12 @@ describe('the pushStatus IPC handler', () => { }); }); + it('lets the browser answer with the on this page last read', async () => { + const { pushStatus } = await makeService(); + await pushStatus({}, from('app-1')); + expect(browser.asked).toEqual({ cached: true }); + }); + it('is off for an app without the permission', async () => { held = false; const { pushStatus } = await makeService(); diff --git a/src/puter-js/src/modules/notifications/index.js b/src/puter-js/src/modules/notifications/index.js index e2da62788..fda363c63 100644 --- a/src/puter-js/src/modules/notifications/index.js +++ b/src/puter-js/src/modules/notifications/index.js @@ -492,9 +492,12 @@ export class NotificationsModule extends EventListener { * failed confirmation is tried again on the next load. * * @param {{ url: string; scope?: string }} worker + * @param {{ background?: boolean }} [options] `background` is a call without + * a click: a browser the user removed in Puter rejects with + * `push_device_removed`, and a rejected token opens no sign-in. * @internal */ - async _enableWebPush(worker) { + async _enableWebPush(worker, { background = false } = {}) { await this.#userChange; this.#useWorker(worker); this.#listenForOptInChanges(); @@ -508,8 +511,8 @@ export class NotificationsModule extends EventListener { worker, onPending: pending, signal, - renewRemoved: true, - interactive: true, + renewRemoved: !background, + interactive: !background, withLock: withPushLock, onAnnounced: () => this.#recordOptIn(true), onSynced: (endpoint) => this.#noteSynced(worker, endpoint), diff --git a/src/puter-js/src/modules/notifications/webPush.test.js b/src/puter-js/src/modules/notifications/webPush.test.js index c3d49ab68..ea1232423 100644 --- a/src/puter-js/src/modules/notifications/webPush.test.js +++ b/src/puter-js/src/modules/notifications/webPush.test.js @@ -2241,6 +2241,77 @@ describe('enable after the user removed this browser in Puter', () => { expect(nav.pushManager.subscribe).toHaveBeenCalledTimes(1); expect(store.get(OPT_IN)).toBe(true); }); + + describe('in the Puter GUI', () => { + const RECEIPT = `handlers:puter:receipt:${ORIGIN}/`; + /** A browser holding a removed subscription and its receipt. */ + const removedHere = () => { + const removed = makeSubscription( + undefined, + 'https://push.example/1', + ); + store.set(RECEIPT, { + endpoint: 'https://push.example/1', + receipt: 'r-1', + }); + const nav = makeNav({ + existing: removed, + active: { scriptURL: `${ORIGIN}/sw.js` }, + }); + nav.pushManager.subscribe.mockResolvedValue( + makeSubscription(undefined, 'https://push.example/2'), + ); + withBrowser(nav); + server((route, body) => { + if (body.subscription.endpoint === 'https://push.example/1') + throw new PuterJSError('removed', 'push_device_removed'); + return { status: 'active', device: { uid: 'd2' } }; + }); + return { removed, nav }; + }; + const announced = () => + mockRequest.mock.calls + .filter(([, , route]) => route === '/push/web/subscriptions') + .map(([, , , body]) => body); + /** Whether each call to `route` could open Puter's sign-in. */ + const reauthOf = (route) => + mockRequest.mock.calls + .filter(([, , r]) => r === route) + .map(([, , , , options]) => options?.interactiveReauth); + + it('replaces the removed subscription for a click', async () => { + const { removed, nav } = removedHere(); + const { module } = makeModule({ env: 'gui' }); + await expect(module.enable()).resolves.toBe(true); + expect(removed.unsubscribe).toHaveBeenCalledTimes(1); + expect(nav.pushManager.subscribe).toHaveBeenCalledTimes(1); + expect(reauthOf('/push/web/key')).toEqual([true]); + }); + + it('leaves it removed in the background, and forgets its receipt', async () => { + const { removed, nav } = removedHere(); + const { module } = makeModule({ env: 'gui' }); + await expect( + module._enableWebPush(workerFor('gui'), { background: true }), + ).rejects.toMatchObject({ code: 'push_device_removed' }); + expect(nav.pushManager.subscribe).not.toHaveBeenCalled(); + expect(removed.unsubscribe).toHaveBeenCalledTimes(1); + expect(announced()).toEqual([ + expect.objectContaining({ receipt: 'r-1' }), + ]); + expect(store.has(RECEIPT)).toBe(false); + }); + + it('opens no sign-in for a rejected token in the background', async () => { + removedHere(); + const { module } = makeModule({ env: 'gui' }); + await module + ._enableWebPush(workerFor('gui'), { background: true }) + .catch(() => {}); + expect(reauthOf('/push/web/key')).toEqual([false]); + expect(reauthOf('/push/web/subscriptions')).toEqual([false]); + }); + }); }); describe('status', () => {