Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions pm-stack/console/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
67 changes: 61 additions & 6 deletions pm-stack/console/public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -943,14 +977,26 @@ 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.")];
}
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 {
Expand All @@ -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;
Expand All @@ -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"),
Expand Down
47 changes: 43 additions & 4 deletions pm-stack/console/src/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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$/,
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
};
}

Expand Down Expand Up @@ -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",
Expand All @@ -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 };
Expand Down
62 changes: 62 additions & 0 deletions pm-stack/console/test/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");
});
Loading