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

+10 -1
View File
@@ -26,7 +26,16 @@ export function ensurePushSubscriptionsTable(db: Database): void {
db.run('CREATE INDEX IF NOT EXISTS idx_push_sub_session ON push_subscriptions(session_id)')
}
/** Deletes the push subscriptions registered by any of the given Better Auth sessions. */
export function deletePushSubscriptionsForSessions(db: Database, sessionIds: string[]): number {
if (sessionIds.length === 0) return 0
const placeholders = sessionIds.map(() => '?').join(', ')
return db
.prepare(`DELETE FROM push_subscriptions WHERE session_id IN (${placeholders})`)
.run(...sessionIds).changes
}
/** Deletes the push subscriptions a revoked Better Auth session registered. */
export function deletePushSubscriptionsForSession(db: Database, sessionId: string): number {
return db.prepare('DELETE FROM push_subscriptions WHERE session_id = ?').run(sessionId).changes
return deletePushSubscriptionsForSessions(db, [sessionId])
}
+1 -1
View File
@@ -244,7 +244,7 @@ try {
await gitAuthService.initialize(ipcServer, db)
logger.info(`Git IPC server running at ${ipcServer.ipcHandlePath}`)
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
opencodeServerManager.setDatabase(db)
detectSandboxCapability()
+11 -4
View File
@@ -1,8 +1,10 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { isAdminConfigured, type AuthInstance } from '../auth'
import { applyClientIpHeaders, resolveSocketIp } from '../auth/client-ip'
import { ENV } from '@opencode-manager/shared/config/env'
import { logger } from '../utils/logger'
import { deletePushSubscriptionsForSessions } from '../db/push-subscriptions'
export function createAuthRoutes(auth: AuthInstance): Hono {
const app = new Hono()
@@ -15,18 +17,21 @@ export function createAuthRoutes(auth: AuthInstance): Hono {
return app
}
export async function syncAdminFromEnv(auth: AuthInstance): Promise<void> {
export async function syncAdminFromEnv(auth: AuthInstance, db: Database): Promise<void> {
if (!isAdminConfigured()) return
const adminEmail = ENV.AUTH.ADMIN_EMAIL!
const adminPassword = ENV.AUTH.ADMIN_PASSWORD!
const ctx = await auth.$context
const existingAdmin = await ctx.internalAdapter.findUserByEmail(adminEmail)
const existingAdmin = await ctx.adapter.findOne<{ id: string }>({
model: 'user',
where: [{ field: 'email', value: adminEmail, mode: 'insensitive' }],
})
if (existingAdmin) {
if (ENV.AUTH.ADMIN_PASSWORD_RESET) {
const credentialAccount = (await ctx.internalAdapter.findAccounts(existingAdmin.user.id))
const credentialAccount = (await ctx.internalAdapter.findAccounts(existingAdmin.id))
.find((account) => account.providerId === 'credential')
if (credentialAccount) {
@@ -37,7 +42,9 @@ export async function syncAdminFromEnv(auth: AuthInstance): Promise<void> {
logger.warn(`No credential account found for ${adminEmail}; skipped the password reset`)
}
await ctx.internalAdapter.deleteUserSessions(existingAdmin.user.id)
const sessions = await ctx.internalAdapter.listSessions(existingAdmin.id)
await ctx.internalAdapter.deleteUserSessions(existingAdmin.id)
deletePushSubscriptionsForSessions(db, sessions.map((session) => session.id))
logger.info(`Admin password reset from environment for ${adminEmail}`)
logger.warn('Remove ADMIN_PASSWORD_RESET=true from environment after password reset')
}
+9 -10
View File
@@ -47,29 +47,28 @@ export function createDevicePairingRoutes(deps: DevicePairingRouteDeps) {
const origin = normalizeDevicePairingOrigin(requestedOrigin)
if (!origin) return c.json({ error: INVALID_ORIGIN_QUERY_MESSAGE }, 400)
return c.json(
resolveDevicePairingAvailability(origin, {
trustedOrigins: resolveTrustedOrigins(),
isDevelopment: isDevelopment(),
}),
)
const { available, reason, message } = resolveDevicePairingAvailability(origin, {
trustedOrigins: resolveTrustedOrigins(),
isDevelopment: isDevelopment(),
})
return c.json({ available, reason, message })
})
app.post('/links', async (c) => {
const body = await parseJsonBody(c, CreateDevicePairingLinksRequestSchema, { allowEmpty: true })
if (!body.ok) return body.response
const origin = c.req.header('origin')
const availability = resolveDevicePairingAvailability(origin, {
const availability = resolveDevicePairingAvailability(c.req.header('origin'), {
trustedOrigins: resolveTrustedOrigins(),
isDevelopment: isDevelopment(),
})
if (!origin || !availability.available) {
if (!availability.available) {
return c.json({ error: availability.message, code: availability.reason }, 400)
}
try {
const originUrl = new URL(origin)
const originUrl = availability.originUrl
const policy = resolveAppLinkPolicy(originUrl, {
allowPrivateNetworkHttp: deps.readAllowPrivateNetworkHttp(),
})
+19 -22
View File
@@ -3,19 +3,23 @@ import {
buildManagerAppLink,
buildManagerBrowserPairingLink,
type AppLinkBlockedReason,
type DevicePairingAvailability,
type DevicePairingLinkWarning,
type DevicePairingLinksResponse,
type DevicePairingUnavailableReason,
type RemoteAccessHeader,
} from '@opencode-manager/shared/schemas'
import { isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
import {
isLoopbackHost,
isPrivateNetworkHost,
isPublicPlainHttpUrl,
parseHttpUrl,
} from '@opencode-manager/shared/utils'
export const MISSING_ORIGIN_MESSAGE =
const MISSING_ORIGIN_MESSAGE =
'The request had no Origin header. Open the Manager at an address listed in AUTH_TRUSTED_ORIGINS to pair a device.'
export const LOOPBACK_ORIGIN_MESSAGE =
const LOOPBACK_ORIGIN_MESSAGE =
'This page is open on localhost, which other devices cannot reach. Open the Manager at its public or LAN address to pair a device.'
export const INSECURE_ORIGIN_MESSAGE =
const INSECURE_ORIGIN_MESSAGE =
'Pairing needs HTTPS on a public address. Serve the Manager over HTTPS, or open it at a private network address.'
type AppLinkPolicy = {
@@ -23,6 +27,10 @@ type AppLinkPolicy = {
warnings: DevicePairingLinkWarning[]
}
type DevicePairingAvailabilityResult =
| { available: true; reason: null; message: null; originUrl: URL }
| { available: false; reason: DevicePairingUnavailableReason; message: string }
type DevicePairingAvailabilityOptions = {
trustedOrigins: string[]
isDevelopment: boolean
@@ -35,37 +43,26 @@ function untrustedOriginMessage(origin: string): string {
function unavailable(
reason: DevicePairingUnavailableReason,
message: string,
): DevicePairingAvailability {
): DevicePairingAvailabilityResult {
return { available: false, reason, message }
}
function parseHttpOrigin(value: string): URL | null {
let url: URL
try {
url = new URL(value)
} catch {
return null
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
return url
}
/** Normalises an address to its origin, or null when it is not an absolute http(s) URL. */
export function normalizeDevicePairingOrigin(value: string): string | null {
return parseHttpOrigin(value)?.origin ?? null
return parseHttpUrl(value)?.origin ?? null
}
/** Reports whether an origin can mint a pairing code, and why it cannot when blocked. */
export function resolveDevicePairingAvailability(
origin: string | undefined,
options: DevicePairingAvailabilityOptions,
): DevicePairingAvailability {
): DevicePairingAvailabilityResult {
if (!origin) return unavailable('untrusted-origin', MISSING_ORIGIN_MESSAGE)
if (!isTrustedOrigin(origin, { requireOrigin: true }, options.trustedOrigins)) {
return unavailable('untrusted-origin', untrustedOriginMessage(origin))
}
const originUrl = parseHttpOrigin(origin)
const originUrl = parseHttpUrl(origin)
if (!originUrl) return unavailable('untrusted-origin', untrustedOriginMessage(origin))
const isLoopback = isLoopbackHost(originUrl.hostname)
@@ -73,11 +70,11 @@ export function resolveDevicePairingAvailability(
return unavailable('loopback', LOOPBACK_ORIGIN_MESSAGE)
}
if (originUrl.protocol === 'http:' && !isLoopback && !isPrivateNetworkHost(originUrl.hostname)) {
if (isPublicPlainHttpUrl(originUrl)) {
return unavailable('insecure-origin', INSECURE_ORIGIN_MESSAGE)
}
return { available: true, reason: null, message: null }
return { available: true, reason: null, message: null, originUrl }
}
/** Decides whether an origin can carry an app link and which warnings it raises. */
+1 -1
View File
@@ -222,7 +222,7 @@ export class NotificationService {
user_id = excluded.user_id,
p256dh = excluded.p256dh,
auth = excluded.auth,
device_name = excluded.device_name,
device_name = COALESCE(excluded.device_name, push_subscriptions.device_name),
session_id = excluded.session_id,
last_used_at = excluded.last_used_at`
)
+1 -1
View File
@@ -78,7 +78,7 @@ describe('createAuth', () => {
body: { email: 'other@example.com', password: 'test-password', name: 'Other' },
})).rejects.toThrow('Registration is disabled')
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
const response = await auth.handler(new Request('http://localhost:5173/api/auth/sign-in/email', {
method: 'POST',
headers: { 'content-type': 'application/json', origin: 'http://localhost:5173' },
+1 -1
View File
@@ -7,7 +7,7 @@ export interface LoggerMocks {
debug: Mock
}
export function loggedArguments(loggerMocks: LoggerMocks): unknown[][] {
function loggedArguments(loggerMocks: LoggerMocks): unknown[][] {
return [...loggerMocks.info.mock.calls, ...loggerMocks.warn.mock.calls, ...loggerMocks.error.mock.calls]
}
+64 -11
View File
@@ -102,6 +102,18 @@ async function findPasswordHash(auth: AuthInstance, userId: string): Promise<str
return account!.password
}
function insertPushSubscription(db: ReturnType<typeof createAuthDatabase>, endpoint: string, sessionId: string | null): void {
db.prepare(
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, session_id, created_at)
VALUES (?, ?, ?, ?, ?, ?)`,
).run('default', endpoint, 'p256dh-key', 'auth-key', sessionId, Date.now())
}
function pushSubscriptionEndpoints(db: ReturnType<typeof createAuthDatabase>): string[] {
return (db.prepare('SELECT endpoint FROM push_subscriptions ORDER BY endpoint').all() as Array<{ endpoint: string }>)
.map((row) => row.endpoint)
}
function createSession(): Session {
return {
session: {
@@ -188,7 +200,7 @@ describe('syncAdminFromEnv', () => {
})
it('does nothing when the admin credentials are not configured', async () => {
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(await countRows(auth, 'user')).toBe(0)
expect(mockLoggerInfo).not.toHaveBeenCalled()
@@ -197,7 +209,7 @@ describe('syncAdminFromEnv', () => {
it('does nothing when only one admin credential is configured', async () => {
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(await countRows(auth, 'user')).toBe(0)
})
@@ -208,7 +220,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(200)
expect((await signInRequest(auth, 'admin@example.com', 'new-password')).status).toBe(401)
@@ -221,20 +233,39 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(await countRows(auth, 'user')).toBe(1)
expect((await signInRequest(auth, 'Admin@Example.com', 'new-password')).status).toBe(200)
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(401)
}, 30000)
it('finds the existing admin user when the stored email differs only by case', async () => {
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'old-password', name: 'Admin' } })
const cookies = await createUserSession(auth, 'admin@example.com', 'old-password')
const adminId = (await auth.api.getSession({ headers: cookies }))!.user.id
db.prepare('UPDATE "user" SET email = ? WHERE id = ?').run('Admin@Example.com', adminId)
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth, db)
const ctx = await auth.$context
expect(await countRows(auth, 'user')).toBe(1)
expect(await ctx.password.verify({
password: 'new-password',
hash: await findPasswordHash(auth, adminId),
})).toBe(true)
}, 30000)
it('resets the credential account password for an existing user', async () => {
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'old-password', name: 'Admin' } })
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect((await signInRequest(auth, 'admin@example.com', 'new-password')).status).toBe(200)
expect((await signInRequest(auth, 'admin@example.com', 'old-password')).status).toBe(401)
@@ -255,12 +286,34 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(await countRows(auth, 'session', adminId)).toBe(0)
expect(await countRows(auth, 'session', otherId)).toBe(otherSessionsBefore)
}, 30000)
it('deletes the push subscriptions of the revoked admin sessions and keeps the others', async () => {
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'admin-password', name: 'Admin' } })
await auth.api.signUpEmail({ body: { email: 'other@example.com', password: 'other-password', name: 'Other' } })
const adminCookies = await createUserSession(auth, 'admin@example.com', 'admin-password')
const otherCookies = await createUserSession(auth, 'other@example.com', 'other-password')
const adminSessionId = (await auth.api.getSession({ headers: adminCookies }))!.session.id
const otherSessionId = (await auth.api.getSession({ headers: otherCookies }))!.session.id
insertPushSubscription(db, 'https://push.example.com/phone', adminSessionId)
insertPushSubscription(db, 'https://push.example.com/tablet', otherSessionId)
insertPushSubscription(db, 'https://push.example.com/legacy', null)
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth, db)
expect(pushSubscriptionEndpoints(db)).toEqual([
'https://push.example.com/legacy',
'https://push.example.com/tablet',
])
}, 30000)
it('runs the session delete hook for every revoked admin session', async () => {
await auth.api.signUpEmail({ body: { email: 'admin@example.com', password: 'admin-password', name: 'Admin' } })
const cookies = await createUserSession(auth, 'admin@example.com', 'admin-password')
@@ -271,7 +324,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(close).toHaveBeenCalledTimes(1)
}, 30000)
@@ -286,7 +339,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(mockLoggerWarn).toHaveBeenCalledWith(expect.stringContaining('No credential account found'))
expect(mockLoggerInfo).toHaveBeenCalledWith(expect.stringContaining('Admin password reset'))
@@ -302,7 +355,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_PASSWORD = 'new-password'
ENV.AUTH.ADMIN_PASSWORD_RESET = true
await expect(syncAdminFromEnv(auth)).rejects.toThrow()
await expect(syncAdminFromEnv(auth, db)).rejects.toThrow()
const ctx = await auth.$context
expect(await ctx.password.verify({
@@ -315,7 +368,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'admin-password'
await syncAdminFromEnv(auth)
await syncAdminFromEnv(auth, db)
expect(await countRows(auth, 'user')).toBe(1)
expect((await signInRequest(auth, 'admin@example.com', 'admin-password')).status).toBe(200)
@@ -326,7 +379,7 @@ describe('syncAdminFromEnv', () => {
ENV.AUTH.ADMIN_EMAIL = 'admin@example.com'
ENV.AUTH.ADMIN_PASSWORD = 'short'
await expect(syncAdminFromEnv(auth)).resolves.toBeUndefined()
await expect(syncAdminFromEnv(auth, db)).resolves.toBeUndefined()
expect(await countRows(auth, 'user')).toBe(0)
expect(mockLoggerError).toHaveBeenCalledWith('Failed to create admin user from environment:', expect.anything())
+43 -1
View File
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { createNotificationRoutes } from '../../src/routes/notifications'
import type { NotificationService } from '../../src/services/notification'
import { NotificationService } from '../../src/services/notification'
import type { Session } from '../../src/auth'
interface NotificationServiceStub {
@@ -144,6 +145,47 @@ describe('Notification Routes', () => {
)
})
it('updates the stored session id and keeps the device name when the same endpoint subscribes again without one', async () => {
const db = new Database(':memory:')
const service = new NotificationService(db)
const endpoint = 'https://push.example.com/phone'
const subscriptionBody = (deviceName?: string) => JSON.stringify({
endpoint,
keys: { p256dh: 'p256dh-key', auth: 'auth-key' },
...(deviceName ? { deviceName } : {}),
})
try {
const subscribes: Array<[sessionId: string, deviceName: string | undefined]> = [
['ses_old', 'Phone'],
['ses_new', undefined],
]
for (const [sessionId, deviceName] of subscribes) {
const sessionApp = new Hono<{ Variables: { session?: Session['session'] } }>()
sessionApp.use('*', async (c, next) => {
c.set('session', { id: sessionId } as Session['session'])
await next()
})
sessionApp.route('/', createNotificationRoutes(service))
const res = await sessionApp.fetch(new Request('http://localhost/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: subscriptionBody(deviceName),
}))
expect(res.status).toBe(200)
}
const rows = db
.prepare('SELECT session_id, device_name FROM push_subscriptions WHERE endpoint = ?')
.all(endpoint)
expect(rows).toEqual([{ session_id: 'ses_new', device_name: 'Phone' }])
} finally {
db.close()
}
})
it('returns 400 for invalid subscription data', async () => {
const res = await app.fetch(new Request('http://localhost/subscribe', {
method: 'POST',
@@ -17,6 +17,7 @@ describe('resolveDevicePairingAvailability', () => {
available: true,
reason: null,
message: null,
originUrl: new URL('https://m.example.com'),
})
})
@@ -78,6 +78,16 @@ describe('push subscription sessions', () => {
expect(service.getSubscriptions(USER_ID)).toHaveLength(1)
})
it('keeps the stored device name when the same endpoint subscribes again without one', () => {
const endpoint = 'https://push.example.com/phone'
service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', 'Phone', 'ses_old')
const resubscribed = service.saveSubscription(USER_ID, endpoint, 'p256dh-key', 'auth-key', undefined, 'ses_new')
expect(resubscribed.deviceName).toBe('Phone')
expect(sessionIdOf(db, endpoint)).toBe('ses_new')
expect(service.getSubscriptions(USER_ID)).toHaveLength(1)
})
it('adds the session id column to a database created before it existed', () => {
const legacyDb = new Database(':memory:')
legacyDb.run(LEGACY_TABLE)
+52 -1
View File
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest'
import { isLoopbackHost, isPrivateNetworkHost } from '@opencode-manager/shared/utils'
import {
isLoopbackHost,
isPrivateNetworkHost,
isPublicPlainHttpUrl,
parseHttpUrl,
} from '@opencode-manager/shared/utils'
describe('isLoopbackHost', () => {
it.each(['localhost', 'LOCALHOST', '127.0.0.1', '127.4.5.6', '::1', '[::1]'])(
@@ -48,3 +53,49 @@ describe('isPrivateNetworkHost', () => {
expect(isPrivateNetworkHost(host)).toBe(false)
})
})
describe('isPublicPlainHttpUrl', () => {
it.each([
'http://example.com',
'http://example.com.',
'http://203.0.113.5:5003',
'http://8.8.8.8:5003/path',
])('treats %s as public plain http', (url) => {
expect(isPublicPlainHttpUrl(new URL(url))).toBe(true)
})
it.each([
'https://example.com',
'https://203.0.113.5:5003',
'http://localhost:5173',
'http://127.0.0.1:5003',
'http://[::1]:5003',
'http://192.168.1.20:5003',
'http://172.16.0.1:5003',
'http://100.64.0.1:5003',
'http://[fd00::1]:5003',
])('treats %s as not public plain http', (url) => {
expect(isPublicPlainHttpUrl(new URL(url))).toBe(false)
})
})
describe('parseHttpUrl', () => {
it('parses an absolute http url', () => {
expect(parseHttpUrl('http://m.example.com:5003/pair?x=1')?.origin).toBe(
'http://m.example.com:5003',
)
})
it('parses an absolute https url with surrounding whitespace', () => {
expect(parseHttpUrl(' https://m.example.com/settings?tab=pairing ')?.origin).toBe(
'https://m.example.com',
)
})
it.each(['', 'not a url', '//m.example.com', 'ocm://link?v=2&kind=manager', 'ftp://example.com'])(
'returns null for %s',
(value) => {
expect(parseHttpUrl(value)).toBeNull()
},
)
})
@@ -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]);
}
+3 -8
View File
@@ -1,5 +1,5 @@
import { z } from "zod";
import { trimUrlTrailingSlashes } from "../utils/url";
import { parseHttpUrl, trimUrlTrailingSlashes } from "../utils/url";
export const REMOTE_ACCESS_HEADER_MAX_COUNT = 8;
export const REMOTE_ACCESS_HEADER_VALUE_MAX_LENGTH = 512;
@@ -204,13 +204,8 @@ export function readPairingCodeFromHash(hash: string): string | null {
/** Parses a browser pairing link into its origin and code, or null when the text is not one. */
export function parseManagerBrowserPairingLink(text: string): { origin: string; code: string } | null {
let url: URL;
try {
url = new URL(text.trim());
} catch {
return null;
}
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
const url = parseHttpUrl(text.trim());
if (!url) return null;
if (url.pathname !== DEVICE_PAIRING_PATH) return null;
const code = readPairingCodeFromHash(url.hash);
return code === null ? null : { origin: url.origin, code };
+22 -5
View File
@@ -3,6 +3,18 @@ export function trimUrlTrailingSlashes(url: string): string {
return url.trim().replace(/\/+$/, '')
}
/** Parses a value into a URL, or returns null when it is not an absolute http(s) URL. */
export function parseHttpUrl(value: string): URL | null {
let url: URL
try {
url = new URL(value)
} catch {
return null
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
return url
}
/** Reports whether two URLs share the same origin; false when either URL is invalid. */
export function haveSameUrlOrigin(first: string, second: string): boolean {
const origin = readUrlOrigin(first)
@@ -36,6 +48,15 @@ export function isPrivateNetworkHost(hostname: string): boolean {
return firstHextet >= 0xfc00 && firstHextet <= 0xfdff
}
/** Reports whether a URL uses plain HTTP on a host other than loopback or a private network. */
export function isPublicPlainHttpUrl(url: URL): boolean {
return (
url.protocol === 'http:' &&
!isLoopbackHost(url.hostname) &&
!isPrivateNetworkHost(url.hostname)
)
}
function normalizeHostname(hostname: string): string {
return hostname.trim().toLowerCase().replace(/^\[/, '').replace(/\]$/, '')
}
@@ -54,9 +75,5 @@ function parseIpv4Octets(host: string): [number, number, number, number] | null
}
function readUrlOrigin(value: string): string | null {
try {
return new URL(value).origin
} catch {
return null
}
return parseHttpUrl(value)?.origin ?? null
}