8000 Add read-only preflight check and confirm push subscription sync by simon-inkie · Pull Request #73 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

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
71 changes: 65 additions & 6 deletions packages/deck/app/components/PushToggle.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/**
* PushToggle.tsx - "enable notifications on this device" affordance.
*
* Lives in the bell dropdown (the notification surface). Four states:
* Lives in the bell dropdown (the notification surface). States:
* - unsupported: no serviceWorker/PushManager/Notification -> render nothing
* - denied: the browser has push blocked -> inert hint
* - subscribed: tap to turn off (unsubscribe + tell the server)
* - out-of-sync: the server says the subscription is not confirmed; tap to repair or turn off
* (an unreachable status route shows the neutral "off" state instead)
* - off: tap to enable (register SW -> permission -> subscribe -> POST)
*
* The VAPID public key is fetched from /api/push-subscribe on demand - no
Expand All @@ -18,8 +20,25 @@
*/
import { useEffect, useState } from "react";
import { Bell, BellOff, BellRing } from "lucide-react";
import { applicationServerKeyString, pushSyncState } from "~/lib/push-sync";

type PushState = "unsupported" | "denied" | "subscribed" | "off" | "busy";
type PushState = "unsupported" | "denied" | "subscribed" | "out-of-sync" | "off" | "busy";

/** true/false from the server, null when it could not be asked. */
async function confirmSubscription(sub: PushSubscription): Promise<boolean | null> {
const response = await fetch("/api/push-subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
intent: "status",
subscription: sub.toJSON(),
applicationServerKey: applicationServerKeyString(sub.options.applicationServerKey),
}),
});
if (!response.ok) return null;
const result = await response.json() as { synced?: boolean };
return result.synced === true;
}

function urlBase64ToUint8Array(base64: string): Uint8Array {
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
Expand Down Expand Up @@ -47,12 +66,15 @@ export function PushToggle() {
}
let cancelled = false;
void (async () => {
let hasSubscription = false;
try {
const reg = await navigator.serviceWorker.getRegistration("/");
const sub = reg ? await reg.pushManager.getSubscription() : null;
10BC8 if (!cancelled) setState(sub ? "subscribed" : "off");
hasSubscription = !!sub;
const confirmed = sub ? await confirmSubscription(sub) : null;
if (!cancelled) setState(pushSyncState(hasSubscription, confirmed));
} catch {
if (!cancelled) setState("off");
if (!cancelled) setState(pushSyncState(hasSubscription, null));
}
})();
return () => {
Expand All @@ -70,8 +92,20 @@ export function PushToggle() {
return;
}
const keyRes = await fetch("/api/push-subscribe");
if (!keyRes.ok) throw new Error("Could not load push configuration");
const { publicKey } = (await keyRes.json()) as { publicKey: string };
const sub = await reg.pushManager.subscribe({
let sub = await reg.pushManager.getSubscription();
if (sub && applicationServerKeyString(sub.options.applicationServerKey) !== publicKey) {
const oldEndpoint = sub.endpoint;
if (!await sub.unsubscribe()) throw new Error("Could not replace subscription");
await fetch("/api/push-subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ intent: "unsubscribe", endpoint: oldEndpoint }),
});
sub = null;
}
sub ??= await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicKey) as BufferSource,
});
Expand All @@ -80,8 +114,9 @@ export function PushToggle() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ intent: "subscribe", subscription: sub.toJSON() }),
});
setState(res.ok ? "subscribed" : "off");
setState(pushSyncState(true, res.ok ? await confirmSubscription(sub) : false));
} catch {
// Key fetch or subscribe failed: nothing is known to be out of sync.
setState("off");
}
}
Expand All @@ -107,6 +142,30 @@ export function PushToggle() {

if (state === "unsupported") return null;

if (state === "out-of-sync") {
return (
<div data-testid="push-toggle" data-push-state="out-of-sync" className="flex flex-col">
<button
type="button"
>
className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs text-foreground/80 hover:bg-muted"
>
<Bell className="size-3.5 shrink-0" aria-hidden="true" />
<span>Notifications out of sync - re-enable on this device</span>
</button>
<button
type="button"
data-testid="push-toggle-off"
>
className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted"
>
<BellOff className="size-3.5 shrink-0" aria-hidden="true" />
<span>Turn notifications off for this device</span>
</button>
</div>
);
}

if (state === "denied") {
return (
<div
Expand Down
15 changes: 15 additions & 0 deletions packages/deck/app/lib/push-sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** A browser subscription alone does not prove this instance can deliver. */
export function pushSyncState(
hasSubscription: boolean,
serverConfirmed: boolean | null
): "off" | "out-of-sync" | "subscribed" {
// null means the status route could not be reached: unknown, so neutral.
if (!hasSubscription || serverConfirmed === null) return "off";
return serverConfirmed ? "subscribed" : "out-of-sync";
}

10BC8 export function applicationServerKeyString(key: ArrayBuffer | null): string | null {
if (!key) return null;
return btoa(String.fromCharCode(...new Uint8Array(key)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
34 changes: 25 additions & 9 deletions packages/deck/app/lib/push.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,26 @@ function confinedWrite(filePath: string, content: string): void {
// VAPID keys - lazy self-provision
// ---------------------------------------------------------------------------

/**
* Return the instance's VAPID keypair, generating + persisting one on first
* call. Generation is idempotent-enough for the single-daemon case (the
* worst concurrent-boot race rewrites the file with a fresh valid pair
* before any subscription exists).
*/
export function getVapidKeys(): VapidKeys {
/** Read the persisted keypair without provisioning or replacing it. */
export function readVapidKeys(): VapidKeys | null {
const file = dataPath("vapid-keys.json");
try {
const parsed = VapidKeysSchema.safeParse(
JSON.parse(fs.readFileSync(file, "utf8"))
);
if (parsed.success) return parsed.data;
} catch {
// Missing or malformed - fall through to generate.
// Status reads must never provision or replace keys.
}
return null;
}

/** Return the instance's keypair, generating and persisting it on first use. */
export function getVapidKeys(): VapidKeys {
const existing = readVapidKeys();
if (existing) return existing;
const fresh = webpush.generateVAPIDKeys();
confinedWrite(file, JSON.stringify(fresh, null, 2) + "\n");
confinedWrite(dataPath("vapid-keys.json"), JSON.stringify(fresh, null, 2) + "\n");
return fresh;
}

Expand Down Expand Up @@ -134,6 +136,20 @@ export function listSubscriptions(): StoredSubscription[] {
return loadState().subscriptions;
}

/** Confirm both the browser key and the complete subscription, without writes. */
export function isSubscriptionSynced(
sub: z.infer<typeof PushSubscriptionSchema>,
applicationServerKey: string
): boolean {
const keys = readVapidKeys();
if (!keys || applicationServerKey !== keys.publicKey) return false;
return listSubscriptions().some((stored) =>
stored.endpoint === sub.endpoint &&
stored.keys.p256dh === sub.keys.p256dh &&
stored.keys.auth === sub.keys.auth
);
}

/** Add (or refresh) a subscription, deduped by endpoint. */
export function addSubscription(
sub: z.infer<typeof PushSubscriptionSchema>,
Expand Down
17 changes: 17 additions & 0 deletions packages/deck/app/routes/api.push-subscribe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* self-provisioned - the client needs it for PushManager.subscribe)
* POST -> intent=subscribe body: subscription JSON (endpoint + keys)
* intent=unsubscribe body: endpoint
* intent=status body: subscription JSON + applicationServerKey
*
* Subscriptions persist in the instance's data root via push.server.ts
* (per-instance = per-user). The watcher (server/push-watcher.mjs) reads
Expand All @@ -19,6 +20,7 @@ import {
addSubscription,
removeSubscription,
PushSubscriptionSchema,
isSubscriptionSynced,
} from "~/lib/push.server";

function json(payload: unknown, status: number): Response {
Expand All @@ -36,6 +38,11 @@ export async function loader(_args: Route.LoaderArgs) {
}

const BodySchema = z.discriminatedUnion("intent", [
z.object({
intent: z.literal("status"),
subscription: PushSubscriptionSchema,
applicationServerKey: z.string().min(1).nullable(),
}),
z.object({
intent: z.literal("subscribe"),
subscription: PushSubscriptionSchema,
Expand Down Expand Up @@ -64,6 +71,16 @@ export async function action({ request }: Route.ActionArgs) {
);
}

if (parsed.data.intent === "status") {
return json({
ok: true,
synced: parsed.data.applicationServerKey !== null && isSubscriptionSynced(
parsed.data.subscription,
parsed.data.applicationServerKey
),
}, 200);
}

if (parsed.data.intent === "subscribe") {
addSubscription(
parsed.data.subscription,
Expand Down
1 change: 1 addition & 0 deletions packages/deck/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"build": "react-router build",
"preflight": "node scripts/preflight.mjs",
"dev:raw": "react-router dev",
"start": "react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc",
Expand Down
Loading
Loading
0