fix(device-pairing): clean up push subscriptions on admin reset and share URL helpers

The admin password reset finds the admin case-insensitively and deletes the push subscriptions of the sessions it ends. The app re-sends its push subscription once per signed-in session so revoke reaches re-signed-in devices, and the upsert keeps the stored device name. Plain-HTTP and URL parsing checks are shared helpers.
This commit is contained in:
Chris Scott committed 2026-10-24 19:26:21 -04:00
1 parent cbe4f7ed9e
commit 6e398c4d40
21 files changed
+540 -85

No files matched your search

+16 -6
View File
@@ -7,6 +7,7 @@ import {
urlBase64ToUint8Array,
} from "@/lib/serviceWorker";
import type { NotificationPreferences } from "@/api/types/settings";
import type { PushSubscriptionRecord } from "@opencode-manager/shared/types";
import { DEFAULT_NOTIFICATION_PREFERENCES } from "@opencode-manager/shared/schemas";
type PermissionState = NotificationPermission | "unsupported";
@@ -16,6 +17,18 @@ function getPermissionState(): PermissionState {
return Notification.permission;
}
export async function sendRegisteredSubscription(
deviceName?: string
): Promise<{ subscription: PushSubscriptionRecord } | null> {
const registration = await getServiceWorkerRegistration();
if (!registration) return null;
const existingSubscription = await registration.pushManager.getSubscription();
if (!existingSubscription) return null;
return notificationsApi.subscribe(existingSubscription.toJSON(), deviceName);
}
export function useNotifications() {
const queryClient = useQueryClient();
const { preferences, updateSettings } = useSettings();
@@ -44,16 +57,13 @@ export function useNotifications() {
const subscribeMutation = useMutation({
mutationFn: async (deviceName?: string) => {
const registered = await sendRegisteredSubscription(deviceName);
if (registered) return registered;
const reg = await getServiceWorkerRegistration();
if (!reg) throw new Error("Service worker not registered");
if (!vapidData?.publicKey) throw new Error("VAPID key not available");
const existingSub = await reg.pushManager.getSubscription();
if (existingSub) {
const json = existingSub.toJSON();
return notificationsApi.subscribe(json, deviceName);
}
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidData.publicKey).buffer as ArrayBuffer,
@@ -0,0 +1,127 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { usePushSubscriptionSessionSync } from './usePushSubscriptionSessionSync'
const authState = vi.hoisted(() => ({ sessionId: null as string | null }))
const serviceWorker = vi.hoisted(() => ({ getServiceWorkerRegistration: vi.fn() }))
const notificationsApi = vi.hoisted(() => ({ subscribe: vi.fn() }))
vi.mock('@/lib/auth-client', () => ({
useSession: () => ({
data: authState.sessionId ? { session: { id: authState.sessionId }, user: { id: 'user-1' } } : null,
}),
}))
vi.mock('@/lib/serviceWorker', () => ({
getServiceWorkerRegistration: serviceWorker.getServiceWorkerRegistration,
urlBase64ToUint8Array: vi.fn(() => new Uint8Array([1, 2, 3])),
}))
vi.mock('@/api/notifications', () => ({ notificationsApi }))
const subscriptionJson = {
endpoint: 'https://push.example.com/phone',
keys: { p256dh: 'p256dh-key', auth: 'auth-key' },
}
function grantNotificationPermission(): void {
Object.defineProperty(window, 'Notification', {
configurable: true,
value: { permission: 'granted' },
})
}
describe('usePushSubscriptionSessionSync', () => {
beforeEach(() => {
vi.clearAllMocks()
authState.sessionId = 'ses_first'
grantNotificationPermission()
serviceWorker.getServiceWorkerRegistration.mockResolvedValue({
pushManager: {
getSubscription: vi.fn().mockResolvedValue({ toJSON: () => subscriptionJson }),
},
})
notificationsApi.subscribe.mockResolvedValue({ subscription: { id: 1 } })
})
afterEach(() => {
Reflect.deleteProperty(window, 'Notification')
})
it('re-sends the registered subscription once a session is signed in', async () => {
renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(notificationsApi.subscribe).toHaveBeenCalledTimes(1)
})
expect(notificationsApi.subscribe).toHaveBeenCalledWith(subscriptionJson, undefined)
})
it('re-sends the registered subscription again after the session changes', async () => {
const { rerender } = renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(notificationsApi.subscribe).toHaveBeenCalledTimes(1)
})
authState.sessionId = 'ses_second'
rerender()
await waitFor(() => {
expect(notificationsApi.subscribe).toHaveBeenCalledTimes(2)
})
expect(notificationsApi.subscribe).toHaveBeenLastCalledWith(subscriptionJson, undefined)
})
it('sends the subscription only once for the same session', async () => {
const { rerender } = renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(notificationsApi.subscribe).toHaveBeenCalledTimes(1)
})
rerender()
await waitFor(() => {
expect(notificationsApi.subscribe).toHaveBeenCalledTimes(1)
})
})
it('does not send while notification permission is not granted', async () => {
Object.defineProperty(window, 'Notification', {
configurable: true,
value: { permission: 'default' },
})
renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(serviceWorker.getServiceWorkerRegistration).not.toHaveBeenCalled()
})
expect(notificationsApi.subscribe).not.toHaveBeenCalled()
})
it('does not send when the browser has no push subscription', async () => {
serviceWorker.getServiceWorkerRegistration.mockResolvedValue({
pushManager: { getSubscription: vi.fn().mockResolvedValue(null) },
})
renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(serviceWorker.getServiceWorkerRegistration).toHaveBeenCalled()
})
expect(notificationsApi.subscribe).not.toHaveBeenCalled()
})
it('does not send before a session is signed in', async () => {
authState.sessionId = null
renderHook(() => usePushSubscriptionSessionSync())
await waitFor(() => {
expect(serviceWorker.getServiceWorkerRegistration).not.toHaveBeenCalled()
})
expect(notificationsApi.subscribe).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,21 @@
import { useEffect, useRef } from "react";
import { useSession } from "@/lib/auth-client";
import { sendRegisteredSubscription } from "@/hooks/useNotifications";
function hasNotificationPermission(): boolean {
return "Notification" in window && Notification.permission === "granted";
}
export function usePushSubscriptionSessionSync(): void {
const { data: authSession } = useSession();
const sessionId = authSession?.session?.id ?? null;
const syncedSessionIdRef = useRef<string | null>(null);
useEffect(() => {
if (!sessionId || !hasNotificationPermission()) return;
if (syncedSessionIdRef.current === sessionId) return;
syncedSessionIdRef.current = sessionId;
void sendRegisteredSubscription().catch(() => {});
}, [sessionId]);
}