Fix web push delivery handling and worker console
Some checks failed
docker-images / resolve-build-targets (push) Successful in 5s
docker-images / build-and-push (admin) (push) Successful in 30s
docker-images / submit-indexnow (push) Has been cancelled
docker-images / build-and-push (frontend) (push) Has been cancelled
docker-images / build-and-push (backend) (push) Has been cancelled
Some checks failed
docker-images / resolve-build-targets (push) Successful in 5s
docker-images / build-and-push (admin) (push) Successful in 30s
docker-images / submit-indexnow (push) Has been cancelled
docker-images / build-and-push (frontend) (push) Has been cancelled
docker-images / build-and-push (backend) (push) Has been cancelled
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
self.addEventListener('push', (event) => {
|
||||
self.addEventListener("push", (event) => {
|
||||
const payload = (() => {
|
||||
if (!event.data) {
|
||||
return {};
|
||||
@@ -13,39 +13,59 @@ self.addEventListener('push', (event) => {
|
||||
}
|
||||
})();
|
||||
|
||||
const title = payload.title || '订阅更新';
|
||||
const url = payload.url || '/';
|
||||
const notifyClients = self.clients
|
||||
.matchAll({ type: "window", includeUncontrolled: true })
|
||||
.then((clients) =>
|
||||
Promise.all(
|
||||
clients.map((client) =>
|
||||
client.postMessage({
|
||||
type: "termi:web-push-received",
|
||||
payload,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const title = payload.title || "订阅更新";
|
||||
const url = payload.url || "/";
|
||||
const options = {
|
||||
body: payload.body || '',
|
||||
icon: payload.icon || '/favicon.svg',
|
||||
badge: payload.badge || '/favicon.ico',
|
||||
tag: payload.tag || 'termi-subscription',
|
||||
body: payload.body || "",
|
||||
icon: payload.icon || "/favicon.svg",
|
||||
badge: payload.badge || "/favicon.ico",
|
||||
tag: payload.tag || "termi-subscription",
|
||||
data: {
|
||||
url,
|
||||
...(payload.data || {}),
|
||||
},
|
||||
};
|
||||
|
||||
event.waitUntil(self.registration.showNotification(title, options));
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
event.notification.close();
|
||||
const targetUrl = event.notification?.data?.url || '/';
|
||||
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
|
||||
for (const client of clients) {
|
||||
if ('focus' in client && client.url === targetUrl) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(targetUrl);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}),
|
||||
Promise.all([
|
||||
self.registration.showNotification(title, options),
|
||||
notifyClients,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener("notificationclick", (event) => {
|
||||
event.notification.close();
|
||||
const targetUrl = event.notification?.data?.url || "/";
|
||||
|
||||
event.waitUntil(
|
||||
self.clients
|
||||
.matchAll({ type: "window", includeUncontrolled: true })
|
||||
.then((clients) => {
|
||||
for (const client of clients) {
|
||||
if ("focus" in client && client.url === targetUrl) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(targetUrl);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -360,7 +360,7 @@ const webPushAvailable = Boolean(webPushPublicKey);
|
||||
import { mountTurnstile, type MountedTurnstile } from '../lib/utils/turnstile';
|
||||
import {
|
||||
ensureBrowserPushSubscription,
|
||||
getBrowserPushSubscription,
|
||||
getBrowserPushSubscriptionState,
|
||||
supportsBrowserPush,
|
||||
} from '../lib/utils/web-push';
|
||||
|
||||
@@ -505,6 +505,14 @@ const webPushAvailable = Boolean(webPushPublicKey);
|
||||
}
|
||||
};
|
||||
|
||||
const forgetSubmitted = () => {
|
||||
try {
|
||||
window.localStorage.removeItem(SUBSCRIBED_KEY);
|
||||
} catch {
|
||||
// Ignore storage failures.
|
||||
}
|
||||
};
|
||||
|
||||
const resetStatus = () => {
|
||||
delete status.dataset.state;
|
||||
status.textContent = defaultStatus;
|
||||
@@ -811,7 +819,19 @@ const webPushAvailable = Boolean(webPushPublicKey);
|
||||
}
|
||||
|
||||
try {
|
||||
const subscription = await getBrowserPushSubscription();
|
||||
const { subscription, stale } = await getBrowserPushSubscriptionState(
|
||||
browserPushPublicKey,
|
||||
);
|
||||
|
||||
if (stale) {
|
||||
forgetSubmitted();
|
||||
setBrowserAvailability({
|
||||
selectable: true,
|
||||
note: '检测到提醒配置已更新,需要重新开启一次提醒。',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (subscription) {
|
||||
rememberSubmitted();
|
||||
setBrowserAvailability({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const SERVICE_WORKER_URL = '/termi-web-push-sw.js';
|
||||
const SERVICE_WORKER_URL = "/termi-web-push-sw.js";
|
||||
|
||||
export type BrowserPushSubscriptionPayload = {
|
||||
endpoint: string;
|
||||
@@ -9,21 +9,26 @@ export type BrowserPushSubscriptionPayload = {
|
||||
};
|
||||
};
|
||||
|
||||
export type BrowserPushSubscriptionState = {
|
||||
subscription: PushSubscription | null;
|
||||
stale: boolean;
|
||||
};
|
||||
|
||||
function ensureBrowserSupport() {
|
||||
if (
|
||||
typeof window === 'undefined' ||
|
||||
!('Notification' in window) ||
|
||||
!('serviceWorker' in navigator) ||
|
||||
!('PushManager' in window)
|
||||
typeof window === "undefined" ||
|
||||
!("Notification" in window) ||
|
||||
!("serviceWorker" in navigator) ||
|
||||
!("PushManager" in window)
|
||||
) {
|
||||
throw new Error('当前浏览器不支持 Web Push。');
|
||||
throw new Error("当前浏览器不支持 Web Push。");
|
||||
}
|
||||
}
|
||||
|
||||
function urlBase64ToUint8Array(base64String: string) {
|
||||
const normalized = base64String.trim();
|
||||
const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
|
||||
const base64 = (normalized + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padding = "=".repeat((4 - (normalized.length % 4)) % 4);
|
||||
const base64 = (normalized + padding).replace(/-/g, "+").replace(/_/g, "/");
|
||||
const binary = window.atob(base64);
|
||||
const output = new Uint8Array(binary.length);
|
||||
|
||||
@@ -34,22 +39,66 @@ function urlBase64ToUint8Array(base64String: string) {
|
||||
return output;
|
||||
}
|
||||
|
||||
function toUint8Array(value: BufferSource | null | undefined) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value instanceof Uint8Array) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value instanceof ArrayBuffer) {
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
|
||||
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
||||
}
|
||||
|
||||
function uint8ArraysEqual(left: Uint8Array | null, right: Uint8Array | null) {
|
||||
if (!left || !right || left.byteLength !== right.byteLength) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let index = 0; index < left.byteLength; index += 1) {
|
||||
if (left[index] !== right[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function subscriptionMatchesPublicKey(
|
||||
subscription: PushSubscription,
|
||||
publicKeyBytes: Uint8Array | null,
|
||||
) {
|
||||
if (!publicKeyBytes) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentKey = toUint8Array(
|
||||
subscription.options?.applicationServerKey ?? null,
|
||||
);
|
||||
return uint8ArraysEqual(currentKey, publicKeyBytes);
|
||||
}
|
||||
|
||||
async function getRegistration() {
|
||||
ensureBrowserSupport();
|
||||
await navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: '/' });
|
||||
await navigator.serviceWorker.register(SERVICE_WORKER_URL, { scope: "/" });
|
||||
return navigator.serviceWorker.ready;
|
||||
}
|
||||
|
||||
function normalizeSubscription(
|
||||
subscription: PushSubscription | PushSubscriptionJSON,
|
||||
): BrowserPushSubscriptionPayload {
|
||||
const json = 'toJSON' in subscription ? subscription.toJSON() : subscription;
|
||||
const endpoint = json.endpoint?.trim() || '';
|
||||
const auth = json.keys?.auth?.trim() || '';
|
||||
const p256dh = json.keys?.p256dh?.trim() || '';
|
||||
const json = "toJSON" in subscription ? subscription.toJSON() : subscription;
|
||||
const endpoint = json.endpoint?.trim() || "";
|
||||
const auth = json.keys?.auth?.trim() || "";
|
||||
const p256dh = json.keys?.p256dh?.trim() || "";
|
||||
|
||||
if (!endpoint || !auth || !p256dh) {
|
||||
throw new Error('浏览器返回的 PushSubscription 不完整。');
|
||||
throw new Error("浏览器返回的 PushSubscription 不完整。");
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -64,20 +113,53 @@ function normalizeSubscription(
|
||||
|
||||
export function supportsBrowserPush() {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
'Notification' in window &&
|
||||
'serviceWorker' in navigator &&
|
||||
'PushManager' in window
|
||||
typeof window !== "undefined" &&
|
||||
"Notification" in window &&
|
||||
"serviceWorker" in navigator &&
|
||||
"PushManager" in window
|
||||
);
|
||||
}
|
||||
|
||||
export async function getBrowserPushSubscription() {
|
||||
export async function getBrowserPushSubscriptionState(
|
||||
publicKey?: string,
|
||||
): Promise<BrowserPushSubscriptionState> {
|
||||
if (!supportsBrowserPush()) {
|
||||
return null;
|
||||
return {
|
||||
subscription: null,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
const registration = await getRegistration();
|
||||
return registration.pushManager.getSubscription();
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
const normalizedPublicKey = publicKey?.trim() || "";
|
||||
const publicKeyBytes = normalizedPublicKey
|
||||
? urlBase64ToUint8Array(normalizedPublicKey)
|
||||
: null;
|
||||
|
||||
if (!subscription) {
|
||||
return {
|
||||
subscription: null,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (!subscriptionMatchesPublicKey(subscription, publicKeyBytes)) {
|
||||
return {
|
||||
subscription: null,
|
||||
stale: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
subscription,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getBrowserPushSubscription(publicKey?: string) {
|
||||
const state = await getBrowserPushSubscriptionState(publicKey);
|
||||
return state.subscription;
|
||||
}
|
||||
|
||||
export async function ensureBrowserPushSubscription(
|
||||
@@ -86,25 +168,34 @@ export async function ensureBrowserPushSubscription(
|
||||
ensureBrowserSupport();
|
||||
|
||||
if (!publicKey.trim()) {
|
||||
throw new Error('Web Push 公钥未配置。');
|
||||
throw new Error("Web Push 公钥未配置。");
|
||||
}
|
||||
|
||||
const permission =
|
||||
Notification.permission === 'granted'
|
||||
? 'granted'
|
||||
Notification.permission === "granted"
|
||||
? "granted"
|
||||
: await Notification.requestPermission();
|
||||
|
||||
if (permission !== 'granted') {
|
||||
throw new Error('浏览器通知权限未开启。');
|
||||
if (permission !== "granted") {
|
||||
throw new Error("浏览器通知权限未开启。");
|
||||
}
|
||||
|
||||
const registration = await getRegistration();
|
||||
const publicKeyBytes = urlBase64ToUint8Array(publicKey);
|
||||
let subscription = await registration.pushManager.getSubscription();
|
||||
|
||||
if (
|
||||
subscription &&
|
||||
!subscriptionMatchesPublicKey(subscription, publicKeyBytes)
|
||||
) {
|
||||
await subscription.unsubscribe().catch(() => undefined);
|
||||
subscription = null;
|
||||
}
|
||||
|
||||
if (!subscription) {
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(publicKey),
|
||||
applicationServerKey: publicKeyBytes,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user