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

@@ -0,0 +1,117 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import type { ReactNode } from 'react'
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router-dom')>()
return { ...actual, createBrowserRouter: vi.fn(() => ({ routes: [] })) }
})
import { AppShell } from './App'
const mocks = vi.hoisted(() => ({
usePushSubscriptionSessionSync: vi.fn(),
}))
vi.mock('@/hooks/usePushSubscriptionSessionSync', () => ({
usePushSubscriptionSessionSync: mocks.usePushSubscriptionSessionSync,
}))
vi.mock('@/hooks/useMobile', () => ({
useSwipeBack: () => ({ bind: () => () => {} }),
useRightEdgeSwipe: () => ({ bind: () => () => {} }),
}))
vi.mock('@/hooks/useMobileTabBar', () => ({
useMobileTabBar: () => ({ openSheet: null, open: vi.fn() }),
}))
vi.mock('@/contexts/SwipeNavigationContext', () => ({
useSwipeNavigation: () => null,
}))
vi.mock('@/contexts/EventContext', () => ({
EventProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
usePermissions: () => ({
current: null,
pendingCount: 0,
respond: vi.fn(),
showDialog: false,
setShowDialog: vi.fn(),
navigateToCurrent: vi.fn(),
viewedSessionId: null,
currentDirectory: null,
currentIsFromDifferentSession: false,
}),
useEventContext: () => ({
getRepoIdForSession: () => null,
sshHostKey: { request: null, respond: vi.fn() },
}),
}))
vi.mock('@/contexts/RepoWorktreesContext', () => ({
RepoWorktreesProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
}))
vi.mock('@/contexts/KeyboardShortcutsContext', () => ({
KeyboardShortcutsProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
}))
vi.mock('@/contexts/OpenCodeServerContext', () => ({
OpenCodeServerProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
isLocalOpenCodeServer: () => true,
}))
vi.mock('@/lib/serviceWorker', () => ({
onNotificationClick: () => () => {},
}))
vi.mock('@/hooks/useAuth', () => ({ useAuth: () => ({ isAuthenticated: true }) }))
vi.mock('@/hooks/useGlobalShortcutActions', () => ({ useGlobalShortcutActions: vi.fn() }))
vi.mock('@/hooks/useSidebarServerSelection', () => ({ useSidebarServerRouteSync: vi.fn() }))
vi.mock('@/hooks/useOpenCodeFailureToast', () => ({ useOpenCodeFailureToast: vi.fn() }))
vi.mock('@/hooks/useOpenCode', () => ({
sessionQueryOptions: () => ({ queryKey: ['session'], queryFn: async () => null, enabled: false }),
}))
vi.mock('@/hooks/useOpenCodeServerActions', () => ({
useOpenCodeServerActions: () => ({
restartServerMutation: { isPending: false },
confirmOpen: false,
setConfirmOpen: vi.fn(),
activeSessionCount: 0,
requestRestart: vi.fn(),
confirmRestart: vi.fn(),
}),
}))
vi.mock('@/components/navigation/DesktopSidebar', () => ({ DesktopSidebar: () => null }))
vi.mock('@/components/navigation/MobileTabBar', () => ({ MobileTabBar: () => null }))
vi.mock('@/components/navigation/MobileSheetHost', () => ({ MobileSheetHost: () => null }))
vi.mock('@/components/settings/SettingsDialog', () => ({ SettingsDialog: () => null }))
vi.mock('@/components/settings/RestartServerDialog', () => ({ RestartServerDialog: () => null }))
vi.mock('@/components/session/PermissionRequestDialog', () => ({ PermissionRequestDialog: () => null }))
vi.mock('@/components/ssh/SSHHostKeyDialog', () => ({ SSHHostKeyDialog: () => null }))
vi.mock('@/components/VersionNotifier', () => ({ VersionNotifier: () => null }))
vi.mock('@/components/PwaUpdatePrompt', () => ({ PwaUpdatePrompt: () => null }))
describe('AppShell', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('mounts the push subscription session sync in the authenticated shell', () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<AppShell />
</MemoryRouter>
</QueryClientProvider>,
)
expect(mocks.usePushSubscriptionSessionSync).toHaveBeenCalledTimes(1)
})
})
+8 -1
View File
@@ -46,6 +46,7 @@ import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions'
import { useSidebarServerRouteSync } from '@/hooks/useSidebarServerSelection'
import { usePushSubscriptionSessionSync } from '@/hooks/usePushSubscriptionSessionSync'
import { sessionQueryOptions } from '@/hooks/useOpenCode'
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
@@ -160,6 +161,11 @@ function SidebarServerRouteSync() {
return null
}
function PushSubscriptionSessionSync() {
usePushSubscriptionSessionSync()
return null
}
function ServerScope({ children }: { children: ReactNode }) {
const { serverId } = useParams<{ serverId: string }>()
@@ -185,7 +191,7 @@ function RootLayout() {
)
}
function AppShell() {
export function AppShell() {
const navigate = useNavigate()
const location = useLocation()
const rootRef = useRef<HTMLDivElement>(null)
@@ -259,6 +265,7 @@ function AppShell() {
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<SidebarServerRouteSync />
<PushSubscriptionSessionSync />
<div className="flex h-dvh w-full min-w-0 flex-col">
<PwaUpdatePrompt />
<div ref={rootRef} className="flex flex-1 min-h-0 w-full min-w-0">
@@ -12,7 +12,7 @@ import {
type OpenCodeServerLink,
type OpenCodeServerTestResult,
} from '@opencode-manager/shared/schemas'
import { haveSameUrlOrigin, isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
import { haveSameUrlOrigin, isPublicPlainHttpUrl, parseHttpUrl } from '@opencode-manager/shared/utils'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
@@ -85,16 +85,8 @@ const serverFormSchema = z.object({
type ServerFormValues = z.infer<typeof serverFormSchema>
function sendsCredentialsInClear(baseUrl: string): boolean {
try {
const url = new URL(baseUrl)
return (
url.protocol === 'http:' &&
!isLoopbackHost(url.hostname) &&
!isPrivateNetworkHost(url.hostname)
)
} catch {
return false
}
const url = parseHttpUrl(baseUrl)
return url !== null && isPublicPlainHttpUrl(url)
}
function buildDefaultValues(server?: OpenCodeServer | null): ServerFormValues {
+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]);
}