Files
puter/src/gui/src/helpers/pushSync.test.js
T
Juan Fernando Castro 4653ff6dae fix(gui): a removed browser stays off, and launches reuse the page's push status (#4549)
* fix(gui): a browser removed from push stays off until its user turns it on

The silent registration on load and app launch no longer replaces a
subscription the user removed in Puter. When the server answers
push_device_removed, the browser's subscription and its receipt are
dropped and the browser is recorded as turned off, so later loads leave
it alone. Turning push on from Settings or a push dialog still replaces
the removed subscription.

* perf(gui): launches reuse the page's last push status

The built-in push client keeps the last registered status it read in
memory, for the same user and subscription. App launches and an app's
puter.notifications.status() answer from it instead of listing devices
again. It is dropped on enable(), disable(), an unregistered answer and
the worker's subscription-changed message, and the Notifications tab
and push dialogs still read fresh, so a new page load always asks the
server.

* fix(notifications): a background enable opens no sign-in, and a page keeps its last push on for five minutes

_enableWebPush takes { background } in place of { renewRemoved }: a call
without a click leaves a removed browser removed and sends its requests
without interactive sign-in.

The desktop's push client keeps the on that enable() read, so the next
cached status lists no devices, and asks the server again once that on is
five minutes old.

* fix(gui): the kept push on belongs to the user whose devices were listed, and a failed enable() keeps none

A status read or enable() that another user's sign-in overlapped keeps no
on, and an enable() that fails drops what a read begun meanwhile kept.
2026-11-12 20:06:23 -07:00

246 lines
12 KiB
JavaScript

// @vitest-environment jsdom
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
window.api_origin = 'https://api.puter.test';
window.auth_token = 'tok-1';
window.gui_params = { pushEnabled: true };
const fakeClient = (status) => ({
enable: vi.fn(async () => ({ deviceUid: 'dev-new' })),
disable: vi.fn(async () => {}),
status: vi.fn(async () => status),
});
const granted = { permission: 'granted' };
const reply = (status, data = {}) => new Response(JSON.stringify(data), { status });
/** Answers each `METHOD path` from `routes`; anything else is a 404. */
const serve = (routes) => {
globalThis.fetch = vi.fn(async (url, init = {}) => {
const handler = routes[`${init.method ?? 'GET'} ${new URL(url).pathname}`];
if ( ! handler ) return reply(404, { code: 'not_found' });
return typeof handler === 'function' ? handler(init) : reply(200, handler);
});
};
let syncBrowserPush;
let registerPushClient;
beforeEach(async () => {
vi.resetModules();
({ syncBrowserPush } = await import('./pushSync.js'));
({ registerPushClient } = await import('./pushClient.js'));
localStorage.clear();
serve({});
});
const off = () => {
const client = fakeClient({ permission: 'granted', registered: false });
registerPushClient(client);
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 () => {
const client = off();
let release;
client.enable.mockImplementation(() => new Promise((resolve) => {
release = resolve;
}));
const deps = { NotificationApi: granted, userUid: 'u-1', holdsPush: vi.fn(async () => true) };
const first = syncBrowserPush({}, deps);
const second = syncBrowserPush({ appUid: 'app-1' }, deps);
await new Promise((resolve) => setTimeout(resolve, 10));
expect(second).toBe(first);
expect(client.enable).toHaveBeenCalledTimes(1);
release({ deviceUid: 'dev-new' });
await expect(first).resolves.toBe('on');
client.status.mockResolvedValue({ permission: 'granted', registered: true, deviceUid: 'dev-new' });
await expect(syncBrowserPush({}, deps)).resolves.toBe('on');
expect(client.enable).toHaveBeenCalledTimes(1);
});
it('does nothing when no app may send pushes', async () => {
const client = off();
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => false })).resolves.toBe('no_app');
expect(client.enable).not.toHaveBeenCalled();
});
it.each([
['the browser has not granted notifications', { NotificationApi: { permission: 'default' }, userUid: 'u-1' }],
['nobody is signed in', { NotificationApi: granted, userUid: undefined }],
])('does nothing when %s', async (_label, deps) => {
const client = off();
await expect(syncBrowserPush({}, { ...deps, holdsPush: async () => true })).resolves.toBe('skipped');
expect(client.status).not.toHaveBeenCalled();
expect(client.enable).not.toHaveBeenCalled();
});
it('leaves a browser the user turned off alone', async () => {
const client = off();
localStorage.setItem('puter.push.browser-off:u-1', '1');
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true })).resolves.toBe('opted_out');
expect(client.status).not.toHaveBeenCalled();
expect(client.enable).not.toHaveBeenCalled();
});
it('keeps another user\'s opt-out to that user', async () => {
const client = off();
localStorage.setItem('puter.push.browser-off:u-2', '1');
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true })).resolves.toBe('on');
expect(client.enable).toHaveBeenCalledTimes(1);
});
it.each([
['on', { permission: 'granted', registered: true, deviceUid: 'dev-1' }],
['blocked', { permission: 'denied', registered: false }],
])('reports %s and does not register again', async (state, status) => {
const client = fakeClient(status);
registerPushClient(client);
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true })).resolves.toBe(state);
expect(client.enable).not.toHaveBeenCalled();
});
it('reports unavailable without a client', async () => {
window.gui_params = { pushEnabled: false };
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true })).resolves.toBe('unavailable');
window.gui_params = { pushEnabled: true };
});
it('reports failed when registering fails or the app check fails', async () => {
const client = off();
client.enable.mockRejectedValue(new Error('no_worker'));
const quiet = [vi.spyOn(console, 'debug'), vi.spyOn(console, 'warn')].map(spy => spy.mockImplementation(() => {}));
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => true })).resolves.toBe('failed');
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1', holdsPush: async () => {
throw new Error('down');
} })).resolves.toBe('failed');
for ( const spy of quiet ) spy.mockRestore();
});
it('asks the server about the launched app', async () => {
const client = off();
const check = vi.fn((init) => reply(200, { permissions: Object.fromEntries(JSON.parse(init.body).permissions.map(p => [p, true])) }));
serve({
'POST /auth/check-permissions': check,
'GET /push/apps': { apps: [{ uid: 'app-1', name: 'chat', puterDevices: true }] },
});
await expect(syncBrowserPush({ appUid: 'app-1' }, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('on');
expect(JSON.parse(check.mock.calls[0][0].body)).toEqual({ permissions: ['notifications:push'], app_uid: 'app-1' });
expect(client.enable).toHaveBeenCalledTimes(1);
});
it('does not count an app a website let in through Web Push only', async () => {
const client = off();
serve({ 'GET /push/apps': { apps: [{ uid: 'app-1', name: 'chat', puterDevices: false }] } });
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('no_app');
serve({
'POST /auth/check-permissions': { permissions: { 'notifications:push': true } },
'GET /push/apps': { apps: [{ uid: 'app-1', name: 'chat', puterDevices: false }] },
});
await expect(syncBrowserPush({ appUid: 'app-1' }, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('no_app');
expect(client.enable).not.toHaveBeenCalled();
serve({
'POST /auth/check-permissions': { permissions: { 'notifications:push': true } },
'GET /push/apps': { apps: [{ uid: 'app-1', name: 'chat', puterDevices: false }, { uid: 'app-2', name: 'mail', puterDevices: true }] },
});
await expect(syncBrowserPush({ appUid: 'app-2' }, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('on');
});
it('asks the server for the apps that may send pushes when no app is named', async () => {
const client = off();
serve({ 'GET /push/apps': { apps: [{ uid: 'app-1', name: 'chat' }] } });
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('on');
expect(client.enable).toHaveBeenCalledTimes(1);
serve({ 'GET /push/apps': { apps: [] } });
await expect(syncBrowserPush({}, { NotificationApi: granted, userUid: 'u-1' })).resolves.toBe('no_app');
});
});