@jskit-ai/push-web 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - `/jskit-sw.js` shows the icon and badge image an app's worker sets in `self.JSKIT_PUSH = { icon, badge }` before loading it, and sets the app icon's count from a notification's `badge` (`setAppBadge`; 0 clears it) where the browser can. `enable({ label })` names the device. `isCurrent(device)` answers whether a device from `GET /api/push` is this one. A browser subscribed before the app used push-web is found by its push manager subscription, so it shows as on.
5
6
  - The notifications section (`PushSettingsSection`, its state in `usePushSettings`) keeps its form on screen and the person's unsaved edits when the device switch is turned or a device is removed; only the first load shows the skeleton. A failed save reads "Your notification settings weren't saved. Try again." and a failed removal "{label} wasn't removed. Try again." (they read "didn't load"), in the shell's snackbar rather than an alert pushing the form down. Each device row and the empty list carry the notifications icon. A quiet hours end the server refuses shows beside that field. Remove sends one request however often it is pressed, and Remove, Save ("Saving…") and the device switch stay focusable while they run (`v-pending`).
6
7
  - The manifest marks `push.core` install-time only (`jskit.capabilities.installRequires`): the client calls push-core's routes and no server feature of push-web requires it, so start-up no longer logs it as a requirement no feature has.
7
8
  - New package: the `client.push` capability (`PushClientProvider`). Registers this browser through JSKIT's own service worker (`/jskit-sw.js`, served by `PushWebFeature`) or this phone through `@capacitor/push-notifications` ^9 (an optional peer) with `@jskit-ai/push-core`, asks permission only from the person's own action, opens a tapped notification's own page and tells the app's `onTap` handlers, forgets this device before every sign-out, and provides the account settings section `push.web.settings.section`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/push-web",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -71,7 +71,7 @@
71
71
  }
72
72
  },
73
73
  "dependencies": {
74
- "@jskit-ai/push-core": "0.1.5"
74
+ "@jskit-ai/push-core": "0.1.6"
75
75
  },
76
76
  "peerDependencies": {
77
77
  "@capacitor/push-notifications": "^9.0.2",
@@ -92,6 +92,7 @@ function createPushClient({ mobile, router, logger }) {
92
92
  enable: registration.enable,
93
93
  disable: registration.disable,
94
94
  current: device.current,
95
+ isCurrent: registration.isCurrent,
95
96
  onTap,
96
97
  start,
97
98
  stop
@@ -208,8 +208,19 @@ function createWebPushDevice({ navigator, notification, storage, serviceWorker }
208
208
  return () => navigator.serviceWorker.removeEventListener("message", listen);
209
209
  }
210
210
 
211
+ /**
212
+ * This browser's registration: the one stored when it subscribed, or, for a browser that subscribed before the app
213
+ * used push-web (nothing stored), the push manager's subscription at the site's root, stored from then on.
214
+ */
211
215
  async function current() {
212
- return stored.read();
216
+ const known = stored.read();
217
+ if (known) return known;
218
+ const registration = await navigator.serviceWorker.getRegistration("/");
219
+ const subscription = await registration?.pushManager.getSubscription();
220
+ if (!subscription) return null;
221
+ const found = { kind: "webpush", token: subscription.endpoint };
222
+ stored.write(found);
223
+ return found;
213
224
  }
214
225
 
215
226
  return Object.freeze({
@@ -15,11 +15,28 @@ const UNSUBSCRIBE_WAIT_MS = 3_000;
15
15
  * @param {string} options.label What the device is called in the person's list, such as "Chrome on Mac".
16
16
  */
17
17
  function createPushRegistration({ device, request, label }) {
18
- /** Asks permission (the person's own action calls this), then registers this device. */
19
- async function enable() {
18
+ /**
19
+ * Asks permission (the person's own action calls this), then registers this device, under `options.label` when the
20
+ * app names it in its own words ("Chrome on Mac"), else the browser's platform.
21
+ * @param {{ label?: string }} [options]
22
+ */
23
+ async function enable(options = {}) {
24
+ const named = String(options.label || "").trim() || label;
20
25
  const overview = await request(PUSH_PATHS.OVERVIEW, { method: "GET" });
21
26
  const registration = await device.subscribe(String(overview.publicKey || ""));
22
- return request(PUSH_PATHS.DEVICES, { method: "POST", body: { ...registration, ...(label ? { label } : {}) } });
27
+ return request(PUSH_PATHS.DEVICES, { method: "POST", body: { ...registration, ...(named ? { label: named } : {}) } });
28
+ }
29
+
30
+ /**
31
+ * Whether a device the overview lists is this one: its `tokenHash` is the hash of this device's own registration, made
32
+ * as push-core makes it (SHA-256 of "kind:token", hex).
33
+ * @param {{ kind: string, tokenHash?: string }} listed
34
+ */
35
+ async function isCurrent(listed) {
36
+ const mine = await device.current();
37
+ if (!mine || !listed?.tokenHash || listed.kind !== mine.kind) return false;
38
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${mine.kind}:${mine.token}`));
39
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("") === listed.tokenHash;
23
40
  }
24
41
 
25
42
  /** Stops notifications on this device: forgotten on the server, then dropped here. */
@@ -43,6 +60,7 @@ function createPushRegistration({ device, request, label }) {
43
60
 
44
61
  return Object.freeze({
45
62
  enable,
63
+ isCurrent,
46
64
  disable,
47
65
  forgetAtSignOut
48
66
  });
@@ -1,7 +1,8 @@
1
1
  // JSKIT's service worker: it shows the server's web push notifications and opens their page when tapped. It caches
2
2
  // nothing, so it never answers a request in place of the server. An app with a worker of its own (an offline page,
3
3
  // cached build files) registers that one instead (`config.push.serviceWorker`), which loads this one first with
4
- // `importScripts("/jskit-sw.js")`.
4
+ // `importScripts("/jskit-sw.js")`. Such a worker may name the notifications' icon and badge image there, read when each
5
+ // push arrives: `self.JSKIT_PUSH = { icon: "/app-icons/icon-192.png", badge: "/app-icons/badge-96.png" }`.
5
6
 
6
7
  // Its handlers are the worker's own events, which last as long as the worker, so none is ever removed.
7
8
 
@@ -13,6 +14,24 @@ function onActivate(event) {
13
14
  event.waitUntil(self.clients.claim());
14
15
  }
15
16
 
17
+ // The app's own image paths for a notification's icon and badge, from self.JSKIT_PUSH; none when it names none.
18
+ function notificationImages() {
19
+ const settings = self.JSKIT_PUSH && typeof self.JSKIT_PUSH === "object" ? self.JSKIT_PUSH : {};
20
+ return Object.fromEntries(["icon", "badge"].filter((name) => typeof settings[name] === "string" && settings[name]).map((name) => [name, settings[name]]));
21
+ }
22
+
23
+ // A message's numeric badge is the count the app's icon shows, where the browser has an app badge; 0 clears it.
24
+ async function showAppBadge(badge) {
25
+ const count = Number(badge);
26
+ if (badge === undefined || badge === null || !Number.isFinite(count) || !self.navigator?.setAppBadge) return;
27
+ try {
28
+ if (count > 0) await self.navigator.setAppBadge(count);
29
+ else await self.navigator.clearAppBadge();
30
+ } catch {
31
+ // The browser keeps no badge for this app (not installed, or the person turned badges off).
32
+ }
33
+ }
34
+
16
35
  function onPush(event) {
17
36
  let message = {};
18
37
  try {
@@ -22,13 +41,17 @@ function onPush(event) {
22
41
  }
23
42
  const title = String(message.title || "");
24
43
  if (!title) return;
25
- event.waitUntil(self.registration.showNotification(title, {
26
- body: String(message.body || ""),
27
- tag: message.group || undefined,
28
- renotify: Boolean(message.group),
29
- data: { url: String(message.url || ""), data: message.data || {} },
30
- actions: Array.isArray(message.actions) ? message.actions.slice(0, 2) : []
31
- }));
44
+ event.waitUntil(Promise.all([
45
+ self.registration.showNotification(title, {
46
+ body: String(message.body || ""),
47
+ ...notificationImages(),
48
+ tag: message.group || undefined,
49
+ renotify: Boolean(message.group),
50
+ data: { url: String(message.url || ""), data: message.data || {} },
51
+ actions: Array.isArray(message.actions) ? message.actions.slice(0, 2) : []
52
+ }),
53
+ showAppBadge(message.badge)
54
+ ]));
32
55
  }
33
56
 
34
57
  // A tap opens only the app's own pages, never another site or scheme.
@@ -138,3 +138,46 @@ test("enable registers with the server; sign-out forgets this device on the serv
138
138
  assert.deepEqual(sent.at(-1), ["POST", "/api/push/devices/forget", { kind: "apns", token: "apns-token" }]);
139
139
  assert.equal(await device.current(), null);
140
140
  });
141
+
142
+ test("a browser that subscribed before the app used push-web is found by its push manager subscription, and stored", async () => {
143
+ const storage = memoryStorage();
144
+ let subscription = { endpoint: "https://fcm.googleapis.com/fcm/send/earlier" };
145
+ const navigator = {
146
+ serviceWorker: {
147
+ getRegistration: async (scope) => (scope === "/" ? { pushManager: { getSubscription: async () => subscription } } : undefined),
148
+ addEventListener() {},
149
+ removeEventListener() {}
150
+ }
151
+ };
152
+ globalThis.PushManager ??= class {};
153
+ const device = createWebPushDevice({ navigator, notification: { permission: "granted" }, storage, serviceWorker: "/jskit-sw.js" });
154
+ assert.deepEqual(await device.current(), { kind: "webpush", token: "https://fcm.googleapis.com/fcm/send/earlier" });
155
+ subscription = null;
156
+ assert.deepEqual(await device.current(), { kind: "webpush", token: "https://fcm.googleapis.com/fcm/send/earlier" }, "stored from then on");
157
+ const none = createWebPushDevice({ navigator, notification: { permission: "granted" }, storage: memoryStorage(), serviceWorker: "/jskit-sw.js" });
158
+ assert.equal(await none.current(), null, "no subscription and nothing stored is no device");
159
+ });
160
+
161
+ test("enable takes the app's own label for the device, and isCurrent tells which listed device is this one", async () => {
162
+ const plugin = fakePushNotifications({ state: "granted" });
163
+ const device = createNativePushDevice({ plugin, platform: "ios", settings: SETTINGS, storage: memoryStorage() });
164
+ const sent = [];
165
+ const registration = createPushRegistration({
166
+ device,
167
+ label: "iOS",
168
+ request: async (path, options) => {
169
+ sent.push([options.method, path, options.body]);
170
+ return path === "/api/push" ? { publicKey: "" } : { ok: true };
171
+ }
172
+ });
173
+ await registration.enable({ label: "Mercbot app on iPhone" });
174
+ assert.equal(sent.at(-1)[2].label, "Mercbot app on iPhone");
175
+ await registration.enable();
176
+ assert.equal(sent.at(-1)[2].label, "iOS", "without one, the default stays");
177
+ // push-core's hash: SHA-256 of "kind:token", hex.
178
+ const { createHash } = await import("node:crypto");
179
+ const hash = (kind, token) => createHash("sha256").update(`${kind}:${token}`).digest("hex");
180
+ assert.equal(await registration.isCurrent({ kind: "apns", tokenHash: hash("apns", "apns-token") }), true);
181
+ assert.equal(await registration.isCurrent({ kind: "apns", tokenHash: hash("apns", "another") }), false);
182
+ assert.equal(await registration.isCurrent({ kind: "fcm", tokenHash: hash("fcm", "apns-token") }), false);
183
+ });
@@ -0,0 +1,48 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import test from "node:test";
4
+ import vm from "node:vm";
5
+
6
+ // push-web's service worker run as a browser runs it, in a context of its own whose `self` is a stand-in worker: what a
7
+ // push shows, with the app's icon and badge images, and the count the app's icon shows.
8
+ const SOURCE = readFileSync(new URL("../src/client/serviceWorker/jskit-sw.js", import.meta.url), "utf8");
9
+
10
+ function worker({ settings, appBadge = true } = {}) {
11
+ const shown = [];
12
+ const badges = [];
13
+ const listeners = new Map();
14
+ const self = {
15
+ ...(settings ? { JSKIT_PUSH: settings } : {}),
16
+ addEventListener: (type, listener) => listeners.set(type, listener),
17
+ registration: { showNotification: async (title, options) => shown.push([title, options]) },
18
+ navigator: appBadge ? { setAppBadge: async (count) => badges.push(count), clearAppBadge: async () => badges.push("cleared") } : {}
19
+ };
20
+ vm.runInNewContext(SOURCE, { self, URL });
21
+ async function push(message) {
22
+ const waits = [];
23
+ listeners.get("push")({ data: { json: () => message }, waitUntil: (promise) => waits.push(promise) });
24
+ await Promise.all(waits);
25
+ }
26
+ return { push, shown, badges };
27
+ }
28
+
29
+ test("a push shows the app's own icon and badge images when its worker names them, and none otherwise", async () => {
30
+ const named = worker({ settings: { icon: "/app-icons/icon-192.png", badge: "/app-icons/badge-96.png" } });
31
+ await named.push({ title: "Ada", body: "Lunch?" });
32
+ assert.equal(named.shown[0][1].icon, "/app-icons/icon-192.png");
33
+ assert.equal(named.shown[0][1].badge, "/app-icons/badge-96.png");
34
+ const plain = worker();
35
+ await plain.push({ title: "Ada" });
36
+ assert.deepEqual([plain.shown[0][1].icon, plain.shown[0][1].badge], [undefined, undefined]);
37
+ });
38
+
39
+ test("a push's numeric badge sets the app icon's count, 0 clears it, and a browser without app badges is left alone", async () => {
40
+ const app = worker();
41
+ await app.push({ title: "Ada", badge: 3 });
42
+ await app.push({ title: "Read", badge: 0 });
43
+ await app.push({ title: "No count" });
44
+ assert.deepEqual(app.badges, [3, "cleared"]);
45
+ const browser = worker({ appBadge: false });
46
+ await browser.push({ title: "Ada", badge: 3 });
47
+ assert.equal(browser.shown.length, 1, "the notification still shows");
48
+ });