diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 8413b174ec..c925713d44 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -49,6 +49,18 @@ subscribes under More, Notifications, and chooses what reaches it: a reply to something asked, something new that needs the owner, new questions, a failed unit. The Android app shows them as its own. +The screen says "On for this device" only when the sender holds this +device too: a browser that said yes while the sender refused or lost its +address is shown as not finished, with one button to finish. It also +says what came of the last notification: how many devices the push +services took it for, and which service refused and with what status. +"Took" is the word, because a push service accepting a message is not +the phone showing it. + +Addresses are accepted only at the push services browsers really name: +Google's (`fcm.googleapis.com`, and `jmt17.google.com`, which a Chrome +off the stable channel gives), Mozilla's, Apple's and Microsoft's. + A unit that runs on a timer (a service with a timer of the same name, such as `pm-git-sync`) is treated differently from one that stays up. Between runs it shows as failed whenever its last run failed, so one bad diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index aa6f2b575f..81ebe4ee6a 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -918,6 +918,40 @@ export function subscriptionState(madeFor, mark, status) { return (status.known || []).includes(mark) ? "keep" : "again"; } +/** Where this device stands: "on" (it is subscribed and the sender has + * it), "unfinished" (the browser said yes but the sender does not have + * this device, so nothing would arrive), or "off". `state` is + * subscriptionState's answer for this device's subscription. */ +export function deviceState(permission, subscribed, state) { + if (!subscribed || permission !== "granted") return "off"; + return state === "keep" ? "on" : "unfinished"; +} + +const SENT_FOR = { + replies: "a reply from the fleet", + needs: "something that needs you", + questions: "a question for you", + trouble: "a unit that failed", + test: "a test", +}; +const devices = (n) => `${n} device${n === 1 ? "" : "s"}`; + +/** What came of the last notification, in a sentence or two. A push + * service taking a message is not the phone showing it, so this says + * "took", not "delivered". */ +export function deliveryNote(last, now = Date.now()) { + if (!last) return "Nothing has been sent yet."; + const said = [`Last sent ${ago(last.at, now) || "at an unknown time"}: ${SENT_FOR[last.class] || "a notification"}.`]; + if (last.sent) said.push(`The push service took it for ${devices(last.sent)}.`); + if (last.failed) { + const first = (last.refused || [])[0]; + const why = first ? `: ${first.host} ${first.status ? `answered ${first.status}` : "did not answer"}` : ""; + said.push(`Not taken for ${devices(last.failed)}${why}.`); + } + if (last.gone) said.push(`${devices(last.gone)} no longer subscribed ${last.gone === 1 ? "was" : "were"} forgotten.`); + return said.join(" "); +} + /** Notifications that are on for this device stay on: nothing is asked, * because the owner already said yes on this device. A device where * they are off is left alone. */ @@ -943,6 +977,13 @@ function keyBytes(b64) { return Uint8Array.from(text, (c) => c.charCodeAt(0)); } +/** What a test send came to, for the line shown when it is done. */ +export function testSaid(r) { + if (r.sent && !r.failed) return `Test sent to ${devices(r.sent)}`; + if (r.sent) return `Test sent to ${devices(r.sent)}; not taken for ${devices(r.failed)}`; + return r.failed ? "The push service did not take the test" : "No device took the test"; +} + async function viewNotify() { if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) { return [empty("This browser cannot receive notifications. On Android, use Chrome or the app.")]; @@ -950,7 +991,12 @@ async function viewNotify() { const status = await api("push"); const reg = await navigator.serviceWorker.getRegistration("/console/"); const sub = reg ? await reg.pushManager.getSubscription() : null; - const on = Boolean(sub) && Notification.permission === "granted"; + // The browser being subscribed is half of it: the sender has to hold + // this device too, or nothing would arrive. + const madeFor = sub?.options?.applicationServerKey; + const state = sub ? subscriptionState(madeFor ? b64url(new Uint8Array(madeFor)) : "", await endpointMark(sub.endpoint), status) : "keep"; + const where = deviceState(Notification.permission, Boolean(sub), state); + const on = where === "on"; const turnOn = async (e) => { e.target.disabled = true; try { @@ -959,8 +1005,14 @@ async function viewNotify() { } const r = await navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }); await navigator.serviceWorker.ready; + // A subscription made for another sender's key cannot be reused. + if (state === "renew") await (await r.pushManager.getSubscription())?.unsubscribe(); const s = await r.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(status.key) }); - await act("push.on", { subscription: s.toJSON(), label: deviceLabel() }, "Notifications are on for this device"); + // Refused by the sender: the reason is on screen, and the button + // is there to press again. + if (!(await act("push.on", { subscription: s.toJSON(), label: deviceLabel() }, "Notifications are on for this device"))) { + e.target.disabled = false; + } } catch (error) { toast(error.message, true); e.target.disabled = false; @@ -973,15 +1025,18 @@ async function viewNotify() { }; return [ card( - h("h3", {}, on ? "On for this device" : "Off for this device"), - h("p", { class: "meta" }, `${status.devices} device${status.devices === 1 ? "" : "s"} subscribed in all.`), + h("h3", {}, on ? "On for this device" : where === "unfinished" ? "Not finished on this device" : "Off for this device"), + where === "unfinished" + ? h("p", { class: "why" }, "This device said yes, but the sender of notifications does not have it, so nothing would arrive here.") + : null, + h("p", { class: "meta" }, `${devices(status.devices)} subscribed in all. ${deliveryNote(status.last)}`), Notification.permission === "denied" ? h("p", { class: "why" }, "This browser is set to block notifications from this site.") : null, h( "div", { class: "row end" }, on ? h("button", { class: "small ghost", onclick: turnOff }, "Turn off") : null, - on ? h("button", { class: "small ghost", onclick: (e) => act("push.test", {}, (r) => (r.sent ? `Test sent to ${r.sent} device${r.sent === 1 ? "" : "s"}` : "No device took the test"), e.target) }, "Send a test") : null, - on ? null : h("button", { onclick: turnOn }, "Turn on for this device"), + on ? h("button", { class: "small ghost", onclick: (e) => act("push.test", {}, testSaid, e.target) }, "Send a test") : null, + on ? null : h("button", { onclick: turnOn }, where === "unfinished" ? "Finish turning on" : "Turn on for this device"), ), ), h("h2", {}, "Tell me when"), diff --git a/pm-stack/console/src/push.ts b/pm-stack/console/src/push.ts index b1440c86e6..b0a1769206 100644 --- a/pm-stack/console/src/push.ts +++ b/pm-stack/console/src/push.ts @@ -37,9 +37,16 @@ const concat = (...parts: Uint8Array[]) => { }; /** Push services a subscription may name. This server posts to the - * endpoint a browser gives it, so the endpoint has to be one of these. */ + * endpoint a browser gives it, so the endpoint has to be one of these. + * + * Chrome names one of two Google hosts: a released Chrome the first, and + * a Chrome that is not on the stable channel (Beta, Dev, Canary, a build + * of one's own) the second. Both are in Chromium's + * components/push_messaging/push_messaging_constants.cc. Leaving the + * second out refuses every such browser when it turns notifications on. */ const PUSH_HOSTS = [ /^fcm\.googleapis\.com$/, + /^jmt17\.google\.com$/, /^([a-z0-9-]+\.)*push\.services\.mozilla\.com$/, /^([a-z0-9-]+\.)*notify\.windows\.com$/, /^([a-z0-9-]+\.)*push\.apple\.com$/, @@ -56,10 +63,26 @@ export interface Subscription { export const CLASSES = ["replies", "needs", "questions", "trouble"] as const; export type Class = (typeof CLASSES)[number]; +/** What came of the last notification that was sent: how many devices + * the push services took it for, and what a service that refused said. + * It is how the owner can tell that notifications arrive without + * waiting for one. */ +export interface Delivery { + at: string; + class: Class | "test"; + sent: number; + gone: number; + failed: number; + /** The push service's host and its HTTP status (0: it did not answer), + * for each device it was not taken for. Never the device's address. */ + refused: { host: string; status: number }[]; +} + interface PushFile { vapid: { publicKey: string; privateJwk: JsonWebKey } | null; subscriptions: Subscription[]; off: Class[]; + last?: Delivery | null; } export function validSubscription(value: unknown): Subscription | null { @@ -165,6 +188,7 @@ export class Push { devices: s.subscriptions.length, known: await Promise.all(s.subscriptions.map((x) => endpointMark(x.endpoint))), classes: Object.fromEntries(CLASSES.map((c) => [c, !s.off.includes(c)])), + last: s.last ?? null, }; } @@ -231,7 +255,10 @@ export class Push { let sent = 0; let failed = 0; const gone: string[] = []; + const refused: Delivery["refused"] = []; + const attempted = s.subscriptions.length; for (const sub of s.subscriptions) { + const host = new URL(sub.endpoint).hostname; try { const res = await this.post(sub.endpoint, { method: "POST", @@ -247,13 +274,25 @@ export class Push { }); if (res.status === 404 || res.status === 410) gone.push(sub.endpoint); else if (res.status >= 200 && res.status < 300) sent++; - else failed++; + else { + failed++; + refused.push({ host, status: res.status }); + } } catch { failed++; + refused.push({ host, status: 0 }); } } - if (gone.length) { - s.subscriptions = s.subscriptions.filter((x) => !gone.includes(x.endpoint)); + if (gone.length) s.subscriptions = s.subscriptions.filter((x) => !gone.includes(x.endpoint)); + if (attempted > 0) { + s.last = { + at: new Date(this.now()).toISOString(), + class: cls, + sent, + gone: gone.length, + failed, + refused: refused.slice(0, 5), + }; await this.save(); } return { sent, gone: gone.length, failed }; diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 1fd7ea1689..c931135a0a 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -9,10 +9,13 @@ import { awayState, band, capital, + deliveryNote, deviceLabel, + deviceState, endpointMark, prCheck, subscriptionState, + testSaid, } from "../public/app.js"; import { androidRelease } from "../src/edge-proto.ts"; import { contact, endpointMark as serverMark } from "../src/push.ts"; @@ -218,3 +221,62 @@ test("a pull request's check says what GitHub said, and nothing it did not", () test("a button's word starts with a capital", () => { expect(["start", "restart", "stop", "", "Logs"].map(capital)).toEqual(["Start", "Restart", "Stop", "", "Logs"]); }); + +test("the Notifications screen says 'on' only when something would arrive here", () => { + // The browser being subscribed is half of it. The other half is the + // sender holding this device: without it nothing arrives, and saying + // "On" would be untrue (a refused address left it so before). + expect(deviceState("granted", true, "keep")).toBe("on"); + expect(deviceState("granted", true, "again")).toBe("unfinished"); + expect(deviceState("granted", true, "renew")).toBe("unfinished"); + expect(deviceState("granted", false, "keep")).toBe("off"); + expect(deviceState("default", true, "keep")).toBe("off"); + expect(deviceState("denied", true, "keep")).toBe("off"); +}); + +test("what came of the last notification is said in plain words, and never as 'delivered'", () => { + const NOW = Date.parse("2026-11-23T05:10:00Z"); + expect(deliveryNote(null, NOW)).toBe("Nothing has been sent yet."); + expect( + deliveryNote({ at: "2026-11-23T05:05:00.000Z", class: "test", sent: 1, gone: 0, failed: 0, refused: [] }, NOW), + ).toBe("Last sent 5 min ago: a test. The push service took it for 1 device."); + expect( + deliveryNote( + { + at: "2026-11-23T03:10:00.000Z", + class: "replies", + sent: 2, + gone: 1, + failed: 1, + refused: [{ host: "fcm.googleapis.com", status: 403 }], + }, + NOW, + ), + ).toBe( + "Last sent 2 h ago: a reply from the fleet. The push service took it for 2 devices. Not taken for 1 device: fcm.googleapis.com answered 403. 1 device no longer subscribed was forgotten.", + ); + // A service that could not be reached at all, and a class this page does not know. + expect( + deliveryNote( + { + at: "2026-11-23T05:09:30.000Z", + class: "later", + sent: 0, + gone: 2, + failed: 2, + refused: [{ host: "updates.push.services.mozilla.com", status: 0 }], + }, + NOW, + ), + ).toBe( + "Last sent just now: a notification. Not taken for 2 devices: updates.push.services.mozilla.com did not answer. 2 devices no longer subscribed were forgotten.", + ); + // An older sender's record without the list of refusals still reads. + expect(deliveryNote({ at: "2026-11-23T05:09:30.000Z", class: "needs", sent: 0, gone: 0, failed: 1 }, NOW)).toBe( + "Last sent just now: something that needs you. Not taken for 1 device.", + ); + expect(testSaid({ sent: 2, gone: 0, failed: 0 })).toBe("Test sent to 2 devices"); + expect(testSaid({ sent: 1, gone: 0, failed: 1 })).toBe("Test sent to 1 device; not taken for 1 device"); + expect(testSaid({ sent: 0, gone: 0, failed: 1 })).toBe("The push service did not take the test"); + expect(testSaid({ sent: 0, gone: 1, failed: 0 })).toBe("No device took the test"); +}); diff --git a/pm-stack/console/test/push.test.ts b/pm-stack/console/test/push.test.ts index b0c949b614..5b7a5bc433 100644 --- a/pm-stack/console/test/push.test.ts +++ b/pm-stack/console/test/push.test.ts @@ -93,7 +93,9 @@ describe("the message a phone receives", () => { })); // It still holds both devices, each known by its mark and not by its address. const marks = [await endpointMark(a.subscription.endpoint), await endpointMark(m.subscription.endpoint)]; - expect(await again.status()).toEqual({ ...status, devices: 2, known: marks }); + // And what came of the send above, which a restart does not lose. + const last = { at: new Date(NOW).toISOString(), class: "replies", sent: 2, gone: 0, failed: 0, refused: [] }; + expect(await again.status()).toEqual({ ...status, devices: 2, known: marks, last }); expect(status.known).toEqual([]); expect(marks[0]).toMatch(/^[A-Za-z0-9_-]{16}$/); expect(marks[0]).not.toBe(marks[1]); @@ -142,10 +144,94 @@ describe("the message a phone receives", () => { } }); + test("what came of the last send is kept: how many it was taken for, and which push service refused", async () => { + const dir = mkdtempSync(join(tmpdir(), "pm-push-")); + try { + const a = await browser(); // Google's + const m = await browser("updates.push.services.mozilla.com"); + const w = await browser("web.push.apple.com"); + const MSG = { title: "t", body: "b", url: "/console/" }; + let answer: (url: string) => number = () => 201; + let now = Date.parse("2026-11-23T05:00:00Z"); + const file = join(dir, "push.json"); + const make = () => + new Push( + fileStore(file), + "mailto:o@example.com", + async (url) => { + const status = answer(url); + if (status < 0) throw new Error("no route to the push service"); + return { status }; + }, + () => now, + ); + const push = make(); + expect((await push.status()).last).toBeNull(); // nothing has been sent + await push.send("replies", MSG); + expect((await push.status()).last).toBeNull(); // with nobody to send to, nothing was + for (const b of [a, m, w]) await push.subscribe(b.subscription, ""); + await push.send("replies", MSG); + expect((await push.status()).last).toEqual({ + at: "2026-11-23T05:00:00.000Z", + class: "replies", + sent: 3, + gone: 0, + failed: 0, + refused: [], + }); + // One service refuses, one cannot be reached, one says the device is gone. + answer = (url) => (url === a.subscription.endpoint ? 403 : url === m.subscription.endpoint ? -1 : 410); + now += 60_000; + await push.send("test", MSG); + const last = (await make().status()).last; // as a restarted service reads it back + expect(last).toEqual({ + at: "2026-11-23T05:01:00.000Z", + class: "test", + sent: 0, + gone: 1, + failed: 2, + refused: [ + { host: "fcm.googleapis.com", status: 403 }, + { host: "updates.push.services.mozilla.com", status: 0 }, + ], + }); + // It names the service, never the device: no address, no key. + for (const secret of ["abc123", a.subscription.keys.auth, a.subscription.keys.p256dh]) { + expect(JSON.stringify(await push.status())).not.toContain(secret); + } + // A class that is switched off sends nothing, and the account stays as it was. + await push.setClass("needs", false); + now += 60_000; + await push.send("needs", MSG); + expect((await push.status()).last?.at).toBe("2026-11-23T05:01:00.000Z"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test("the server only posts to push services", async () => { const good = (await browser()).subscription; expect(validSubscription(good)).toEqual(good); + // What browsers really name. The second Google host is the one a + // Chrome off the stable channel gives (a real Chrome 153 did, when + // this was checked against Google's service); both are in Chromium's + // push_messaging_constants.cc. + for (const endpoint of [ + "https://fcm.googleapis.com/fcm/send/dQw:APA91b", + "https://fcm.googleapis.com/wp/dQw:APA91b", + "https://jmt17.google.com/fcm/send/dQw:APA91b", + "https://updates.push.services.mozilla.com/wpush/v2/gAAAA", + "https://web.push.apple.com/QGx", + "https://wns2-by3p.notify.windows.com/w/?token=AwYAAAB", + ]) { + expect(validSubscription({ ...good, endpoint })?.endpoint).toBe(endpoint); + } for (const endpoint of [ + "https://jmt17.google.com.evil.example/fcm/send/x", + "https://x.jmt17.google.com/fcm/send/x", + "https://jmt18.google.com/fcm/send/x", + "https://www.google.com/fcm/send/x", + "https://google.com/fcm/send/x", "http://fcm.googleapis.com/fcm/send/x", // not https "https://127.0.0.1:4870/api/alerts", // this machine "https://fcm.googleapis.com.evil.example/x", diff --git a/pm-stack/console/test/sw.test.ts b/pm-stack/console/test/sw.test.ts new file mode 100644 index 0000000000..568c5502ae --- /dev/null +++ b/pm-stack/console/test/sw.test.ts @@ -0,0 +1,131 @@ +// The service worker: what the phone shows when a notification is +// pushed, and where a tap on it goes. +// +// Oracles: the worker file itself is run, against a stand-in for the +// browser's worker scope that records what it is asked to do. The +// expected notifications are written out by hand. That the same file +// shows the same notification in a real Chrome, handed a message the way +// Chrome hands one over on arrival, was checked by hand when this was +// written (DevTools ServiceWorker.deliverPushMessage). +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +interface Shown { + title: string; + options: { body: string; tag?: string; renotify: boolean; icon: string; badge: string; data: { url: string } }; +} + +function worker(windows: { url: string; canNavigate?: boolean }[] = []) { + const listeners: Record void> = {}; + const shown: Shown[] = []; + const did: string[] = []; + const scope = { + addEventListener: (name: string, fn: (event: unknown) => void) => { + listeners[name] = fn; + }, + skipWaiting: () => did.push("skipWaiting"), + registration: { + showNotification: async (title: string, options: Shown["options"]) => { + shown.push({ title, options }); + }, + }, + clients: { + claim: async () => did.push("claim"), + matchAll: async () => + windows.map((w) => ({ + url: w.url, + focus: async () => did.push(`focus ${w.url}`), + ...(w.canNavigate === false ? {} : { navigate: async (to: string) => did.push(`navigate ${to}`) }), + })), + openWindow: async (to: string) => did.push(`open ${to}`), + }, + }; + new Function("self", readFileSync(join(import.meta.dir, "../public/sw.js"), "utf8"))(scope); + /** Deliver an event and wait for everything it asked the browser to wait for. */ + const fire = async (name: string, event: Record) => { + const waits: Promise[] = []; + listeners[name]({ ...event, waitUntil: (p: Promise) => waits.push(p) }); + await Promise.all(waits); + }; + return { shown, did, fire, listeners }; +} + +const pushed = (text: string | null) => ({ + data: text === null ? null : { json: () => JSON.parse(text) }, +}); + +test("a pushed message is shown as the notification it describes", async () => { + const w = worker(); + await w.fire( + "push", + pushed( + JSON.stringify({ + title: "The fleet replied on #12501", + body: "Done — “quoted” ✓", + url: "/console/#ask", + tag: "ask-12501", + class: "replies", + }), + ), + ); + expect(w.shown).toEqual([ + { + title: "The fleet replied on #12501", + options: { + body: "Done — “quoted” ✓", + tag: "ask-12501", + renotify: true, // a second message about the same thing sounds again, in place of the first + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#ask" }, + }, + }, + ]); +}); + +test("a message the worker cannot read still shows something, as the browser requires", async () => { + // A push that shows nothing makes Chrome show its own "this site has + // been updated in the background" and counts against the site. + const w = worker(); + await w.fire("push", pushed("not json at all")); + await w.fire("push", pushed(null)); + await w.fire("push", pushed(JSON.stringify({ title: "No tag", url: "/console/#needs" }))); + expect(w.shown.map((s) => [s.title, s.options.body, s.options.tag, s.options.renotify, s.options.data.url])).toEqual([ + ["PM", "", undefined, false, "/console/"], + ["PM", "", undefined, false, "/console/"], + ["No tag", "", undefined, false, "/console/#needs"], + ]); +}); + +test("a tap opens the screen the notification is about, in the app that is already open", async () => { + const tap = (url?: string) => { + const closed: string[] = []; + return { closed, event: { notification: { close: () => closed.push("closed"), data: url ? { url } : undefined } } }; + }; + // The app is open: it is brought forward and taken to the screen. + const open = worker([{ url: "https://example.org/elsewhere" }, { url: "https://pm.security.cab/console/#now" }]); + const t = tap("/console/#ask"); + await open.fire("notificationclick", t.event); + expect(t.closed).toEqual(["closed"]); + expect(open.did).toEqual(["focus https://pm.security.cab/console/#now", "navigate /console/#ask"]); + // A window that cannot be navigated is still brought forward. + const fixed = worker([{ url: "https://pm.security.cab/console/", canNavigate: false }]); + await fixed.fire("notificationclick", tap("/console/#needs").event); + expect(fixed.did).toEqual(["focus https://pm.security.cab/console/"]); + // The app is not open: a window is opened on the screen. + const closed = worker([{ url: "https://example.org/elsewhere" }]); + await closed.fire("notificationclick", tap("/console/#more/services").event); + expect(closed.did).toEqual(["open /console/#more/services"]); + // A notification that names no screen opens the app. + const bare = worker(); + await bare.fire("notificationclick", tap().event); + expect(bare.did).toEqual(["open /console/"]); +}); + +test("a new worker takes over at once, so a fix to it does not wait for every tab to close", async () => { + const w = worker(); + await w.fire("install", {}); + await w.fire("activate", {}); + expect(w.did).toEqual(["skipWaiting", "claim"]); +});