mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
feat(notifications): Web Push delivers notifications to every device, even with TREK closed
A fourth built-in channel next to email, webhook and ntfy. Browsers register per device, the server encrypts per RFC 8291 and signs per RFC 8292 with node:crypto and sends only to known push services through the SSRF guard. The event matrix decides per category what arrives by push; admins switch the channel on under Notifications. VAPID keys come from the environment or are generated once, only while neither stored row exists, and kept encrypted. A pair that does not decrypt or match is never overwritten and never swapped for another one: push stays off with an error in the log and every device stays registered until the key is fixed. The subject is VAPID_SUBJECT, then an https APP_URL, then the project URL. Only chat messages collapse into one notification per trip, and a replacement still alerts. A 403 removes a device only after three failures in a row; 404 and 410 remove it at once. Password change, reset and an admin setting a password drop the user's devices with the other credentials. The request log redacts subscriptions and endpoints, boot errors print *** for every secret variable, and logout forgets the device with a plain fetch so an expired session cannot redirect midway. Addresses discussion #894.
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* FE-PUSH-API-001 to FE-PUSH-API-005: the Web Push device endpoints.
|
||||
*
|
||||
* One line per endpoint and no logic, which is why a slip here is quiet: a
|
||||
* wrong path or a body under the wrong key does not throw, the server answers
|
||||
* 400 or 404 and push simply never arrives. So each call is driven through MSW
|
||||
* with its verb, path and body pinned, and a failure has to reach the caller
|
||||
* intact, because `webPush.ts` decides from it whether to roll a subscription
|
||||
* back.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { http, HttpResponse, type JsonBodyType } from 'msw'
|
||||
import type { PushSubscriptionInput } from '@trek/shared'
|
||||
import { server } from '../../tests/helpers/msw/server'
|
||||
import { pushApi } from './push'
|
||||
|
||||
const BASE = '/api/notifications/push'
|
||||
|
||||
let seen: { method: string; url: string; body: unknown } | null = null
|
||||
|
||||
function record<T extends JsonBodyType>(data: T) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const text = await request.text()
|
||||
seen = { method: request.method, url: new URL(request.url).pathname, body: text ? JSON.parse(text) : undefined }
|
||||
return HttpResponse.json(data)
|
||||
}
|
||||
}
|
||||
|
||||
const subscription: PushSubscriptionInput = {
|
||||
endpoint: 'https://fcm.googleapis.com/fcm/send/abc',
|
||||
expirationTime: null,
|
||||
keys: { p256dh: 'BPk', auth: 'aGk' },
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
seen = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('pushApi', () => {
|
||||
it('FE-PUSH-API-001: reads the public key', async () => {
|
||||
server.use(http.get(`${BASE}/public-key`, record({ publicKey: 'BAECAwQ' })))
|
||||
await expect(pushApi.getPublicKey()).resolves.toEqual({ publicKey: 'BAECAwQ' })
|
||||
expect(seen).toMatchObject({ method: 'GET', url: `${BASE}/public-key` })
|
||||
})
|
||||
|
||||
it('FE-PUSH-API-002: registers the subscription under `subscription`', async () => {
|
||||
server.use(http.post(`${BASE}/subscriptions`, record({ success: true, devices: 2 })))
|
||||
await expect(pushApi.subscribe(subscription)).resolves.toEqual({ success: true, devices: 2 })
|
||||
expect(seen).toEqual({ method: 'POST', url: `${BASE}/subscriptions`, body: { subscription } })
|
||||
})
|
||||
|
||||
it('FE-PUSH-API-003: forgets a device by its endpoint, in a DELETE body', async () => {
|
||||
server.use(http.delete(`${BASE}/subscriptions`, record({ success: true })))
|
||||
await expect(pushApi.unsubscribe(subscription.endpoint)).resolves.toEqual({ success: true })
|
||||
expect(seen).toEqual({ method: 'DELETE', url: `${BASE}/subscriptions`, body: { endpoint: subscription.endpoint } })
|
||||
})
|
||||
|
||||
it('FE-PUSH-API-004: a refusal reaches the caller instead of passing as success', async () => {
|
||||
server.use(http.post(`${BASE}/subscriptions`, () => HttpResponse.json({ error: 'Unsupported push service' }, { status: 400 })))
|
||||
await expect(pushApi.subscribe(subscription)).rejects.toMatchObject({ response: { status: 400 } })
|
||||
})
|
||||
|
||||
it('FE-PUSH-API-005: the DELETE answer is checked against the shared contract, like the subscribe answer', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
server.use(http.delete(`${BASE}/subscriptions`, record({ success: false })))
|
||||
await expect(pushApi.unsubscribe(subscription.endpoint)).resolves.toEqual({ success: false })
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[api] push.unsubscribe: response did not match the @trek/shared schema',
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import apiClient, { parseInDev } from './client'
|
||||
import {
|
||||
pushPublicKeyResultSchema,
|
||||
pushSubscribeResultSchema,
|
||||
pushUnsubscribeResultSchema,
|
||||
type PushPublicKeyResult,
|
||||
type PushSubscribeRequest,
|
||||
type PushSubscribeResult,
|
||||
type PushSubscriptionInput,
|
||||
type PushUnsubscribeRequest,
|
||||
type PushUnsubscribeResult,
|
||||
} from '@trek/shared'
|
||||
|
||||
/**
|
||||
* The Web Push device endpoints, in their own file rather than in the
|
||||
* `client.ts` god module. Types come from the shared contracts, so a server
|
||||
* change the client has not caught up with is a typecheck failure rather than
|
||||
* a runtime surprise.
|
||||
*
|
||||
* These calls are online only by nature: a subscription is a device talking to
|
||||
* the server and to the browser's push service at the same moment, so there is
|
||||
* nothing to queue or to cache. `push/webPush.ts` is the only caller. The one
|
||||
* DELETE that does not come through here is the logout teardown's: it is a
|
||||
* plain fetch in webPush.ts, so a session that already ran out cannot set off
|
||||
* apiClient's 401 redirect in the middle of a logout.
|
||||
*/
|
||||
export const pushApi = {
|
||||
/** The VAPID public key a browser subscribes with. */
|
||||
getPublicKey: (): Promise<PushPublicKeyResult> =>
|
||||
apiClient
|
||||
.get('/notifications/push/public-key')
|
||||
.then(r => parseInDev(pushPublicKeyResultSchema, r.data, 'push.publicKey')),
|
||||
|
||||
/** Registers this device. Repeating it for the same endpoint only refreshes the row. */
|
||||
subscribe: (subscription: PushSubscriptionInput): Promise<PushSubscribeResult> => {
|
||||
const body: PushSubscribeRequest = { subscription }
|
||||
return apiClient
|
||||
.post('/notifications/push/subscriptions', body)
|
||||
.then(r => parseInDev(pushSubscribeResultSchema, r.data, 'push.subscribe'))
|
||||
},
|
||||
|
||||
/** Forgets one device, by the endpoint its subscription delivers to. */
|
||||
unsubscribe: (endpoint: string): Promise<PushUnsubscribeResult> => {
|
||||
const body: PushUnsubscribeRequest = { endpoint }
|
||||
return apiClient
|
||||
.delete('/notifications/push/subscriptions', { data: body })
|
||||
.then(r => parseInDev(pushUnsubscribeResultSchema, r.data, 'push.unsubscribe'))
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* FE-ADMCHAN-001 to FE-ADMCHAN-008: the admin's channel switches, shared by
|
||||
* the desktop Notifications tab and the phone section.
|
||||
*
|
||||
* Every switch rewrites one comma-separated app setting. The two things that
|
||||
* must never happen are the ones a rebuild-from-booleans used to do: drop an id
|
||||
* this build does not know (a plugin channel, or a newer built-in), and leave
|
||||
* the screen claiming a state the server refused to store.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
BUILTIN_CHANNEL_ORDER,
|
||||
parseChannelList,
|
||||
serializeChannelList,
|
||||
SWITCH_ONLY_CHANNELS,
|
||||
toggleChannelList,
|
||||
useNotificationChannels,
|
||||
} from './useNotificationChannels'
|
||||
|
||||
const updateAppSettings = vi.hoisted(() => vi.fn())
|
||||
vi.mock('../../api/client', () => ({ authApi: { updateAppSettings } }))
|
||||
|
||||
const t = (key: string) => (key === 'common.error' ? 'Error' : key)
|
||||
|
||||
function mount(initial: Record<string, string>) {
|
||||
const toast = { error: vi.fn() }
|
||||
const hook = renderHook(() => {
|
||||
const [smtpValues, setSmtpValues] = useState(initial)
|
||||
return { smtpValues, channels: useNotificationChannels({ smtpValues, setSmtpValues, toast }, t) }
|
||||
})
|
||||
return { hook, toast }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
updateAppSettings.mockReset()
|
||||
updateAppSettings.mockResolvedValue({})
|
||||
})
|
||||
|
||||
describe('the stored list', () => {
|
||||
it('FE-ADMCHAN-001: reads the plural setting, the legacy singular one, and none', () => {
|
||||
expect(parseChannelList({ notification_channels: 'email, push ,plugin-gotify' })).toEqual(['email', 'push', 'plugin-gotify'])
|
||||
expect(parseChannelList({ notification_channel: 'webhook' })).toEqual(['webhook'])
|
||||
expect(parseChannelList({ notification_channels: 'none' })).toEqual([])
|
||||
expect(parseChannelList({})).toEqual([])
|
||||
expect(parseChannelList({ notification_channels: 'email,' })).toEqual(['email'])
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-002: writes built-ins in their fixed order and keeps every other id', () => {
|
||||
expect(serializeChannelList(['plugin-gotify', 'push', 'email'])).toBe('email,push,plugin-gotify')
|
||||
expect(serializeChannelList([])).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-003: flips exactly one id', () => {
|
||||
expect(toggleChannelList(['email', 'plugin-gotify'], 'push')).toBe('email,push,plugin-gotify')
|
||||
expect(toggleChannelList(['email', 'push'], 'push')).toBe('email')
|
||||
expect(toggleChannelList(['push'], 'push')).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-004: Web Push is a built-in with its own switch card', () => {
|
||||
expect(BUILTIN_CHANNEL_ORDER).toEqual(['email', 'webhook', 'ntfy', 'push'])
|
||||
expect(SWITCH_ONLY_CHANNELS.map(c => c.id)).toEqual(['webhook', 'ntfy', 'push'])
|
||||
expect(SWITCH_ONLY_CHANNELS[2]).toEqual({
|
||||
id: 'push',
|
||||
titleKey: 'admin.notifications.webPushPanel.title',
|
||||
hintKey: 'admin.notifications.webPushPanel.hint',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('useNotificationChannels', () => {
|
||||
it('FE-ADMCHAN-005: answers which channels are on', () => {
|
||||
const { hook } = mount({ notification_channels: 'email,push' })
|
||||
expect(hook.result.current.channels.isActive('push')).toBe(true)
|
||||
expect(hook.result.current.channels.isActive('ntfy')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-006: switching one on saves the whole list and shows it at once', async () => {
|
||||
const { hook, toast } = mount({ notification_channels: 'email,plugin-gotify' })
|
||||
await act(() => hook.result.current.channels.toggle('push'))
|
||||
expect(updateAppSettings).toHaveBeenCalledWith({ notification_channels: 'email,push,plugin-gotify' })
|
||||
expect(hook.result.current.smtpValues.notification_channels).toBe('email,push,plugin-gotify')
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-007: a failed save puts the previous list back and says so', async () => {
|
||||
updateAppSettings.mockRejectedValueOnce(new Error('500'))
|
||||
const { hook, toast } = mount({ notification_channels: 'email' })
|
||||
await act(() => hook.result.current.channels.toggle('push'))
|
||||
expect(updateAppSettings).toHaveBeenCalledWith({ notification_channels: 'email,push' })
|
||||
expect(hook.result.current.smtpValues.notification_channels).toBe('email')
|
||||
expect(hook.result.current.channels.isActive('push')).toBe(false)
|
||||
expect(toast.error).toHaveBeenCalledWith('Error')
|
||||
})
|
||||
|
||||
it('FE-ADMCHAN-008: the rollback writes the normalised form, never an id less', async () => {
|
||||
updateAppSettings.mockRejectedValueOnce(new Error('500'))
|
||||
const { hook } = mount({ notification_channels: 'plugin-gotify, email' })
|
||||
await act(() => hook.result.current.channels.toggle('webhook'))
|
||||
expect(hook.result.current.smtpValues.notification_channels).toBe('email,plugin-gotify')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared'
|
||||
import { authApi } from '../../api/client'
|
||||
import type { TranslationFn } from '../../types'
|
||||
|
||||
/**
|
||||
* The admin's channel switches, shared by the desktop Notifications tab and its
|
||||
* phone twin. Both used to carry their own copy of a three-boolean
|
||||
* `setChannels`, and a fourth channel would have meant a fourth argument in
|
||||
* two places; SonarCloud's duplication budget has no room for that either.
|
||||
*
|
||||
* All switches write one app setting, `notification_channels`, a comma
|
||||
* separated list of channel ids. Ids this build does not know (a plugin
|
||||
* channel, or one a newer server added) must survive a toggle untouched, so
|
||||
* the list is edited, never rebuilt from the switches.
|
||||
*/
|
||||
|
||||
/** The built-in channels, in the order they are written to the list. Other ids follow as stored. */
|
||||
export const BUILTIN_CHANNEL_ORDER: readonly string[] = ['email', 'webhook', 'ntfy', WEB_PUSH_CHANNEL_ID]
|
||||
|
||||
/** The channels whose admin card is only a title, a hint and the switch (email carries the SMTP form). */
|
||||
export const SWITCH_ONLY_CHANNELS: ReadonlyArray<{ id: string; titleKey: string; hintKey: string }> = [
|
||||
{ id: 'webhook', titleKey: 'admin.notifications.webhookPanel.title', hintKey: 'admin.webhook.hint' },
|
||||
{ id: 'ntfy', titleKey: 'admin.notifications.ntfy', hintKey: 'admin.ntfy.hint' },
|
||||
{
|
||||
id: WEB_PUSH_CHANNEL_ID,
|
||||
titleKey: 'admin.notifications.webPushPanel.title',
|
||||
hintKey: 'admin.notifications.webPushPanel.hint',
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* The active ids, from `notification_channels` or, on installs that predate
|
||||
* it, the singular `notification_channel`. 'none' is the stored empty list.
|
||||
*/
|
||||
export function parseChannelList(values: Record<string, string>): string[] {
|
||||
const raw = values.notification_channels ?? values.notification_channel ?? 'none'
|
||||
if (raw === 'none') return []
|
||||
return raw
|
||||
.split(',')
|
||||
.map(id => id.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
/** The stored form: built-ins in their fixed order, then every other id as it was, or 'none'. */
|
||||
export function serializeChannelList(active: readonly string[]): string {
|
||||
const builtins = BUILTIN_CHANNEL_ORDER.filter(id => active.includes(id))
|
||||
const others = active.filter(id => !BUILTIN_CHANNEL_ORDER.includes(id))
|
||||
return [...builtins, ...others].join(',') || 'none'
|
||||
}
|
||||
|
||||
/** The stored list with `id` switched the other way. */
|
||||
export function toggleChannelList(active: readonly string[], id: string): string {
|
||||
return serializeChannelList(active.includes(id) ? active.filter(c => c !== id) : [...active, id])
|
||||
}
|
||||
|
||||
interface ChannelSettingsHost {
|
||||
smtpValues: Record<string, string>
|
||||
setSmtpValues: Dispatch<SetStateAction<Record<string, string>>>
|
||||
toast: { error: (message: string) => void }
|
||||
}
|
||||
|
||||
export interface NotificationChannelSwitches {
|
||||
isActive: (id: string) => boolean
|
||||
/** Flips one channel and saves the list; puts the old list back and toasts when the save fails. */
|
||||
toggle: (id: string) => Promise<void>
|
||||
}
|
||||
|
||||
export function useNotificationChannels(
|
||||
{ smtpValues, setSmtpValues, toast }: ChannelSettingsHost,
|
||||
t: TranslationFn,
|
||||
): NotificationChannelSwitches {
|
||||
const active = parseChannelList(smtpValues)
|
||||
|
||||
const toggle = async (id: string) => {
|
||||
const next = toggleChannelList(active, id)
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: next }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notification_channels: next })
|
||||
} catch {
|
||||
const reverted = serializeChannelList(active)
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: reverted }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
return { isActive: id => active.includes(id), toggle }
|
||||
}
|
||||
@@ -1185,3 +1185,47 @@ describe('NotificationsTab — webhook and channel-test failures', () => {
|
||||
expect(await screen.findByText('Test failed.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Web Push (#894)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// The Push column comes from the server like every other; what this tab adds is
|
||||
// the per-device card, shown only while the admin has the channel switched on.
|
||||
// jsdom has no push APIs, so the real hook reads this "browser" as unable to
|
||||
// receive push, which is exactly what the card must then say.
|
||||
|
||||
const pushMatrix = (active: boolean) => ({
|
||||
preferences: { trip_invite: { inapp: true, push: true } },
|
||||
channels: [
|
||||
{ id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },
|
||||
{ id: 'push', source: 'builtin', labelKey: 'settings.notificationPreferences.push', active, configured: false },
|
||||
],
|
||||
event_types: ['trip_invite'],
|
||||
implemented_combos: { trip_invite: ['inapp', 'push'] },
|
||||
});
|
||||
|
||||
describe('NotificationsTab: Web Push', () => {
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PUSH-001: an active push channel gets its column and the device card', async () => {
|
||||
mockMatrix(pushMatrix(true));
|
||||
render(<NotificationsTab />);
|
||||
|
||||
expect(await screen.findByText('Push notifications on this device')).toBeInTheDocument();
|
||||
expect(screen.getByText('Push')).toBeInTheDocument();
|
||||
expect(await screen.findByRole('status')).toHaveTextContent(/push/i);
|
||||
});
|
||||
|
||||
it('FE-COMP-NOTIFICATIONS-PUSH-002: no card and no column while the admin has push off', async () => {
|
||||
mockMatrix(pushMatrix(false));
|
||||
render(<NotificationsTab />);
|
||||
|
||||
await screen.findByText(/in-app/i);
|
||||
expect(screen.queryByText('Push notifications on this device')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Push')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { Lock } from 'lucide-react'
|
||||
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { notificationsApi, settingsApi } from '../../api/client'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import ToggleSwitch from './ToggleSwitch'
|
||||
import Section from './Section'
|
||||
import WebPushCard from './WebPushCard'
|
||||
|
||||
interface ChannelDescriptor {
|
||||
id: string
|
||||
@@ -323,6 +325,9 @@ export default function NotificationsTab(): React.ReactElement {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Per device rather than per account: the column below picks the events,
|
||||
this card decides whether this browser is one of the places they go. */}
|
||||
{hasChannel(WEB_PUSH_CHANNEL_ID) && <WebPushCard />}
|
||||
{pluginChannels.map(ch => (
|
||||
<div key={ch.id} style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
|
||||
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* FE-COMP-WEBPUSHCARD-001 to FE-COMP-WEBPUSHCARD-004: the desktop device card.
|
||||
*
|
||||
* Markup only: `useWebPush` is mocked and has its own spec, so these cases pin
|
||||
* what each hook state puts on screen and that the buttons reach the hook.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import type { WebPushCardState } from '../../hooks/useWebPush'
|
||||
import WebPushCard from './WebPushCard'
|
||||
|
||||
const hookState = vi.hoisted(() => ({ current: null as unknown as WebPushCardState }))
|
||||
vi.mock('../../hooks/useWebPush', () => ({ useWebPush: () => hookState.current }))
|
||||
|
||||
function state(over: Partial<WebPushCardState> = {}): WebPushCardState {
|
||||
return {
|
||||
state: 'off',
|
||||
stateText: null,
|
||||
canSwitch: true,
|
||||
on: false,
|
||||
switchLabel: 'Turn on for this device',
|
||||
busy: false,
|
||||
canTest: false,
|
||||
toggle: vi.fn(),
|
||||
sendTest: vi.fn(),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
hookState.current = state()
|
||||
})
|
||||
|
||||
describe('WebPushCard', () => {
|
||||
it('FE-COMP-WEBPUSHCARD-001: explains itself and offers to switch on', async () => {
|
||||
render(<WebPushCard />)
|
||||
expect(screen.getByText('Push notifications on this device')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Shows TREK notifications on this device/)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
|
||||
const turnOn = screen.getByRole('button', { name: 'Turn on for this device' })
|
||||
expect(turnOn.className).toContain('bg-accent')
|
||||
expect(screen.getByRole('button', { name: 'Send test' })).toBeDisabled()
|
||||
|
||||
await userEvent.click(turnOn)
|
||||
expect(hookState.current.toggle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-WEBPUSHCARD-002: when on, says so, offers to switch off and to test', async () => {
|
||||
hookState.current = state({ state: 'on', on: true, stateText: 'On for this device', switchLabel: 'Turn off for this device', canTest: true })
|
||||
render(<WebPushCard />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('On for this device')
|
||||
expect(screen.getByRole('button', { name: 'Turn off for this device' }).className).not.toContain('bg-accent')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Send test' }))
|
||||
expect(hookState.current.sendTest).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-WEBPUSHCARD-003: a state that cannot be switched shows its sentence and no buttons', () => {
|
||||
hookState.current = state({ state: 'ios-install', canSwitch: false, stateText: 'Add TREK to the Home Screen first.' })
|
||||
render(<WebPushCard />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Add TREK to the Home Screen first.')
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-WEBPUSHCARD-004: the switch is disabled while busy', () => {
|
||||
hookState.current = state({ busy: true })
|
||||
render(<WebPushCard />)
|
||||
expect(screen.getByRole('button', { name: 'Turn on for this device' })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import React from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useWebPush } from '../../hooks/useWebPush'
|
||||
|
||||
/**
|
||||
* The "Push notifications on this device" card of the Notifications tab. Only
|
||||
* markup: the logic is `useWebPush`, shared with the phone's `MWebPushCard`.
|
||||
* The tab renders it while the admin has the push channel switched on.
|
||||
*/
|
||||
export default function WebPushCard(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const push = useWebPush()
|
||||
|
||||
return (
|
||||
<div className="mb-4 rounded-lg border border-edge bg-surface-secondary p-3">
|
||||
<p className="mb-1 text-caption font-semibold text-content-secondary">{t('settings.webPush.title')}</p>
|
||||
<p className="mb-2 text-caption text-content-faint">{t('settings.webPush.hint')}</p>
|
||||
{push.stateText && (
|
||||
<p role="status" className="mb-2 text-caption text-content-secondary">
|
||||
{push.stateText}
|
||||
</p>
|
||||
)}
|
||||
{push.canSwitch && (
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={push.toggle}
|
||||
disabled={push.busy}
|
||||
className={`rounded-md px-3 py-1.5 text-caption disabled:cursor-not-allowed disabled:opacity-60 ${
|
||||
push.on ? 'border border-edge bg-transparent text-content-secondary' : 'bg-accent text-accent-text'
|
||||
}`}
|
||||
>
|
||||
{push.switchLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={push.sendTest}
|
||||
disabled={!push.canTest}
|
||||
className="rounded-md border border-edge bg-transparent px-3 py-1.5 text-caption text-content-secondary disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('settings.notificationPreferences.sendTest')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export const settingsTabContexts: HelpContext[] = [
|
||||
tab('settings-display', 'sliders', 3, [{ slug: GENERAL }]),
|
||||
tab('settings-appearance', 'palette', 4, [{ slug: APPEARANCE }]),
|
||||
tab('settings-map', 'map', 3, [{ slug: MAP }]),
|
||||
tab('settings-notifications', 'bell', 3, [{ slug: NOTIFICATIONS }]),
|
||||
tab('settings-notifications', 'bell', 4, [{ slug: NOTIFICATIONS }]),
|
||||
tab('settings-integrations', 'plug', 4, [{ slug: SETTINGS, anchor: 'integrations-tab' }, { slug: 'MCP-Setup' }, { slug: 'Photo-Providers' }]),
|
||||
tab('settings-offline', 'cloudOff', 4, [{ slug: OFFLINE }]),
|
||||
tab('settings-account', 'user', 4, [{ slug: SETTINGS, anchor: 'account-tab-summary' }, { slug: 'Two-Factor-Authentication' }, { slug: 'Passkeys' }]),
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* FE-WEBPUSH-HOOK-001 to FE-WEBPUSH-HOOK-015: the one hook behind the desktop
|
||||
* and phone "Push notifications on this device" cards.
|
||||
*
|
||||
* The browser glue (`push/webPush.ts`) has its own spec against a fake browser
|
||||
* and is mocked here, so these cases are about what the card does with it:
|
||||
*
|
||||
* 1. **Every state has its sentence.** Unsupported, insecure, "install first",
|
||||
* blocked and on each read differently, and "off" adds nothing to the hint.
|
||||
* 2. **The gesture.** The key and the registration are fetched on mount, so
|
||||
* the click can hand them straight to `enableWebPush` in the same tick.
|
||||
* 3. **The browser is re-read** after every switch and when the page becomes
|
||||
* visible again, so the card never shows a state of its own invention.
|
||||
* 4. **Toasts only for real failures.** A block or a dismissed prompt is the
|
||||
* user's answer, not an error.
|
||||
*
|
||||
* Translation is the real provider, so the sentences asserted are the shipped
|
||||
* English.
|
||||
*/
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { TranslationProvider } from '../i18n/TranslationContext'
|
||||
import { WebPushError, type WebPushDeviceState } from '../push/webPush'
|
||||
import { useWebPush } from './useWebPush'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
vi.mock('../components/shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
|
||||
|
||||
const push = vi.hoisted(() => ({
|
||||
readWebPushDeviceState: vi.fn(),
|
||||
getWebPushSupport: vi.fn(),
|
||||
loadPushPublicKey: vi.fn(),
|
||||
waitForPushRegistration: vi.fn(),
|
||||
enableWebPush: vi.fn(),
|
||||
disableWebPush: vi.fn(),
|
||||
}))
|
||||
vi.mock('../push/webPush', async importOriginal => {
|
||||
const actual = await importOriginal<typeof import('../push/webPush')>()
|
||||
return { ...actual, ...push }
|
||||
})
|
||||
|
||||
const testChannel = vi.hoisted(() => vi.fn())
|
||||
vi.mock('../api/client', () => ({ notificationsApi: { testChannel } }))
|
||||
|
||||
const REGISTRATION = { scope: '/' } as unknown as ServiceWorkerRegistration
|
||||
|
||||
const EN = {
|
||||
on: 'On for this device',
|
||||
enable: 'Turn on for this device',
|
||||
disable: 'Turn off for this device',
|
||||
unsupported: 'This browser cannot receive push notifications.',
|
||||
insecure: 'Push needs TREK to be opened over HTTPS.',
|
||||
iosInstall: 'On iPhone and iPad, add TREK to the Home Screen first and open it from there.',
|
||||
denied: 'Notifications are blocked for TREK in this browser. Allow them in the browser settings, then try again.',
|
||||
failed: 'Push could not be turned on for this device.',
|
||||
testSuccess: 'Test notification sent.',
|
||||
testFailed: 'Test failed.',
|
||||
}
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) => createElement(TranslationProvider, null, children)
|
||||
|
||||
async function mounted(state: WebPushDeviceState) {
|
||||
push.readWebPushDeviceState.mockResolvedValue(state)
|
||||
const hook = renderHook(() => useWebPush(), { wrapper })
|
||||
await waitFor(() => expect(hook.result.current.state).toBe(state))
|
||||
return hook
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
push.getWebPushSupport.mockReturnValue({ supported: true, reason: null })
|
||||
push.loadPushPublicKey.mockResolvedValue('BAECAwQ')
|
||||
push.waitForPushRegistration.mockResolvedValue(REGISTRATION)
|
||||
push.enableWebPush.mockResolvedValue(undefined)
|
||||
push.disableWebPush.mockResolvedValue(undefined)
|
||||
testChannel.mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('useWebPush: what the card says', () => {
|
||||
it('FE-WEBPUSH-HOOK-001: nothing is claimed before the device has been read', () => {
|
||||
push.readWebPushDeviceState.mockReturnValue(new Promise(() => {}))
|
||||
const { result } = renderHook(() => useWebPush(), { wrapper })
|
||||
expect(result.current.state).toBeNull()
|
||||
expect(result.current.stateText).toBeNull()
|
||||
expect(result.current.canSwitch).toBe(false)
|
||||
expect(result.current.canTest).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['unsupported', EN.unsupported],
|
||||
['insecure', EN.insecure],
|
||||
['ios-install', EN.iosInstall],
|
||||
['denied', EN.denied],
|
||||
] as const)('FE-WEBPUSH-HOOK-002: %s has its own sentence and no switch', async (state, text) => {
|
||||
const { result } = await mounted(state)
|
||||
expect(result.current.stateText).toBe(text)
|
||||
expect(result.current.canSwitch).toBe(false)
|
||||
expect(result.current.canTest).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-003: off offers to switch on and adds no sentence', async () => {
|
||||
const { result } = await mounted('off')
|
||||
expect(result.current.stateText).toBeNull()
|
||||
expect(result.current.canSwitch).toBe(true)
|
||||
expect(result.current.on).toBe(false)
|
||||
expect(result.current.switchLabel).toBe(EN.enable)
|
||||
expect(result.current.canTest).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-004: on says so, offers to switch off and allows a test', async () => {
|
||||
const { result } = await mounted('on')
|
||||
expect(result.current.stateText).toBe(EN.on)
|
||||
expect(result.current.on).toBe(true)
|
||||
expect(result.current.switchLabel).toBe(EN.disable)
|
||||
expect(result.current.canTest).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useWebPush: ahead of the click', () => {
|
||||
it('FE-WEBPUSH-HOOK-005: fetches the key and the registration on mount where push is supported', async () => {
|
||||
await mounted('off')
|
||||
expect(push.loadPushPublicKey).toHaveBeenCalledTimes(1)
|
||||
expect(push.waitForPushRegistration).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-006: fetches neither where push cannot work', async () => {
|
||||
push.getWebPushSupport.mockReturnValue({ supported: false, reason: 'insecure' })
|
||||
await mounted('insecure')
|
||||
expect(push.loadPushPublicKey).not.toHaveBeenCalled()
|
||||
expect(push.waitForPushRegistration).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useWebPush: switching', () => {
|
||||
it('FE-WEBPUSH-HOOK-007: switching on hands the prefetched key and registration over in the same tick', async () => {
|
||||
const hook = await mounted('off')
|
||||
await waitFor(() => expect(push.waitForPushRegistration).toHaveBeenCalled())
|
||||
await act(async () => {})
|
||||
const pending = deferred<void>()
|
||||
push.enableWebPush.mockReturnValueOnce(pending.promise)
|
||||
|
||||
act(() => hook.result.current.toggle())
|
||||
expect(push.enableWebPush).toHaveBeenCalledWith('BAECAwQ', REGISTRATION)
|
||||
expect(hook.result.current.busy).toBe(true)
|
||||
|
||||
push.readWebPushDeviceState.mockResolvedValue('on')
|
||||
await act(async () => pending.resolve())
|
||||
await waitFor(() => expect(hook.result.current.state).toBe('on'))
|
||||
expect(hook.result.current.busy).toBe(false)
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-008: without a prefetched key it fetches one first, and fails cleanly without', async () => {
|
||||
push.loadPushPublicKey.mockResolvedValueOnce(null).mockResolvedValueOnce('LATEKEY')
|
||||
const hook = await mounted('off')
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(push.enableWebPush).toHaveBeenCalledWith('LATEKEY', REGISTRATION))
|
||||
|
||||
push.loadPushPublicKey.mockResolvedValueOnce(null)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
await waitFor(() => expect(hook.result.current.busy).toBe(false))
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(EN.failed))
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-009: a block or a dismissed prompt is an answer, not an error', async () => {
|
||||
const hook = await mounted('off')
|
||||
push.enableWebPush.mockRejectedValueOnce(new WebPushError('dismissed'))
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(hook.result.current.busy).toBe(false))
|
||||
|
||||
push.enableWebPush.mockRejectedValueOnce(new WebPushError('denied'))
|
||||
push.readWebPushDeviceState.mockResolvedValue('denied')
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(hook.result.current.state).toBe('denied'))
|
||||
expect(hook.result.current.stateText).toBe(EN.denied)
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-010: a failure to switch on is toasted and the device read again', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const hook = await mounted('off')
|
||||
push.enableWebPush.mockRejectedValueOnce(new WebPushError('failed'))
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(EN.failed))
|
||||
expect(push.readWebPushDeviceState).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-011: switching off goes through disableWebPush', async () => {
|
||||
const hook = await mounted('on')
|
||||
push.readWebPushDeviceState.mockResolvedValue('off')
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(hook.result.current.state).toBe('off'))
|
||||
expect(push.disableWebPush).toHaveBeenCalledTimes(1)
|
||||
expect(push.enableWebPush).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-012: a browser that refuses to unsubscribe is toasted and stays on', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const hook = await mounted('on')
|
||||
push.disableWebPush.mockRejectedValueOnce(new Error('refused'))
|
||||
await act(async () => hook.result.current.toggle())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'))
|
||||
await waitFor(() => expect(hook.result.current.busy).toBe(false))
|
||||
expect(hook.result.current.state).toBe('on')
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-013: a second click while busy, or with nothing to switch, does nothing', async () => {
|
||||
const hook = await mounted('off')
|
||||
push.enableWebPush.mockReturnValueOnce(new Promise(() => {}))
|
||||
act(() => hook.result.current.toggle())
|
||||
act(() => hook.result.current.toggle())
|
||||
expect(push.enableWebPush).toHaveBeenCalledTimes(1)
|
||||
|
||||
const denied = await mounted('denied')
|
||||
act(() => denied.result.current.toggle())
|
||||
expect(push.enableWebPush).toHaveBeenCalledTimes(1)
|
||||
expect(push.disableWebPush).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useWebPush: the rest', () => {
|
||||
it('FE-WEBPUSH-HOOK-014: the test goes through the generic channel route', async () => {
|
||||
const hook = await mounted('on')
|
||||
const pending = deferred<{ success: boolean; error?: string }>()
|
||||
testChannel.mockReturnValueOnce(pending.promise)
|
||||
act(() => hook.result.current.sendTest())
|
||||
expect(testChannel).toHaveBeenCalledWith('push')
|
||||
expect(hook.result.current.canTest).toBe(false)
|
||||
act(() => hook.result.current.sendTest())
|
||||
expect(testChannel).toHaveBeenCalledTimes(1)
|
||||
await act(async () => pending.resolve({ success: true }))
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.testSuccess)
|
||||
expect(hook.result.current.canTest).toBe(true)
|
||||
|
||||
testChannel.mockResolvedValueOnce({ success: false, error: 'No devices' })
|
||||
await act(async () => hook.result.current.sendTest())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('No devices'))
|
||||
|
||||
testChannel.mockResolvedValueOnce({ success: false })
|
||||
await act(async () => hook.result.current.sendTest())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(EN.testFailed))
|
||||
|
||||
testChannel.mockRejectedValueOnce(new Error('timeout'))
|
||||
toast.error.mockClear()
|
||||
await act(async () => hook.result.current.sendTest())
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(EN.testFailed))
|
||||
})
|
||||
|
||||
it('FE-WEBPUSH-HOOK-015: coming back to the page reads the device again, until unmount', async () => {
|
||||
const hook = await mounted('denied')
|
||||
push.readWebPushDeviceState.mockResolvedValue('off')
|
||||
const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
|
||||
act(() => {
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
})
|
||||
expect(push.readWebPushDeviceState).toHaveBeenCalledTimes(1)
|
||||
|
||||
visibility.mockReturnValue('visible')
|
||||
act(() => {
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
})
|
||||
await waitFor(() => expect(hook.result.current.state).toBe('off'))
|
||||
|
||||
hook.unmount()
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
expect(push.readWebPushDeviceState).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared'
|
||||
import { notificationsApi } from '../api/client'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { useToast } from '../components/shared/Toast'
|
||||
import {
|
||||
disableWebPush,
|
||||
enableWebPush,
|
||||
getWebPushSupport,
|
||||
loadPushPublicKey,
|
||||
readWebPushDeviceState,
|
||||
waitForPushRegistration,
|
||||
WebPushError,
|
||||
type WebPushDeviceState,
|
||||
} from '../push/webPush'
|
||||
|
||||
/**
|
||||
* Everything the "Push notifications on this device" card does, in one hook.
|
||||
*
|
||||
* Shared by the desktop Settings tab and its phone twin on purpose: the two
|
||||
* shells render different markup around identical logic, and SonarCloud's 3%
|
||||
* duplication budget on new code has no room for a second copy
|
||||
* (`useDawarichConnection` is the same pattern for the same reason).
|
||||
*
|
||||
* The browser is the only record of whether this device is subscribed, so the
|
||||
* hook keeps no copy of its own beyond the last reading, and reads again after
|
||||
* every switch and whenever the page comes back into view (which is how a user
|
||||
* returns from unblocking notifications in the browser's site settings).
|
||||
*/
|
||||
export interface WebPushCardState {
|
||||
/** Null until the first look at this device has finished. */
|
||||
state: WebPushDeviceState | null
|
||||
/** The sentence for that state, already translated; null when the hint says it all. */
|
||||
stateText: string | null
|
||||
/** Push is possible here and not blocked, so the card offers the switch. */
|
||||
canSwitch: boolean
|
||||
on: boolean
|
||||
switchLabel: string
|
||||
busy: boolean
|
||||
canTest: boolean
|
||||
toggle: () => void
|
||||
sendTest: () => void
|
||||
}
|
||||
|
||||
const STATE_TEXT_KEYS: Partial<Record<WebPushDeviceState, string>> = {
|
||||
unsupported: 'settings.webPush.unsupported',
|
||||
insecure: 'settings.webPush.insecure',
|
||||
'ios-install': 'settings.webPush.iosInstall',
|
||||
denied: 'settings.webPush.denied',
|
||||
on: 'settings.webPush.enabled',
|
||||
}
|
||||
|
||||
export function useWebPush(): WebPushCardState {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const [state, setState] = useState<WebPushDeviceState | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [testing, setTesting] = useState(false)
|
||||
const publicKey = useRef<string | null>(null)
|
||||
const registration = useRef<ServiceWorkerRegistration | null>(null)
|
||||
const mounted = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
let cancelled = false
|
||||
const look = () => {
|
||||
void readWebPushDeviceState().then(next => {
|
||||
if (!cancelled) setState(next)
|
||||
})
|
||||
}
|
||||
look()
|
||||
if (getWebPushSupport().supported) {
|
||||
// Fetched before any click. WebKit honours the permission prompt and
|
||||
// subscribe() only inside the user's gesture, and awaiting either of
|
||||
// these in the click handler would spend it.
|
||||
void loadPushPublicKey().then(key => {
|
||||
if (!cancelled) publicKey.current = key
|
||||
})
|
||||
void waitForPushRegistration().then(reg => {
|
||||
if (!cancelled) registration.current = reg
|
||||
})
|
||||
}
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === 'visible') look()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisible)
|
||||
return () => {
|
||||
cancelled = true
|
||||
mounted.current = false
|
||||
document.removeEventListener('visibilitychange', onVisible)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const settle = async () => {
|
||||
const next = await readWebPushDeviceState()
|
||||
if (!mounted.current) return
|
||||
setState(next)
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
const switchOn = (): Promise<void> => {
|
||||
const key = publicKey.current
|
||||
if (key) return enableWebPush(key, registration.current)
|
||||
// The key could not be fetched ahead of time. Fetching it now may cost the
|
||||
// gesture on WebKit, but it is the only way left to try.
|
||||
return loadPushPublicKey().then(late => {
|
||||
if (!late) throw new WebPushError('failed', 'no public key')
|
||||
return enableWebPush(late, registration.current)
|
||||
})
|
||||
}
|
||||
|
||||
const toggle = () => {
|
||||
if (busy || (state !== 'on' && state !== 'off')) return
|
||||
const turningOn = state === 'off'
|
||||
setBusy(true)
|
||||
const action = turningOn ? switchOn() : disableWebPush()
|
||||
action
|
||||
.catch(err => {
|
||||
if (!mounted.current) return
|
||||
// A block or a dismissed prompt is the user's answer, and the card
|
||||
// shows the first on its own; only a real failure deserves a toast.
|
||||
if (err instanceof WebPushError && (err.code === 'denied' || err.code === 'dismissed')) return
|
||||
console.warn('[push] switching this device failed', err)
|
||||
toast.error(turningOn ? t('settings.webPush.failed') : t('common.error'))
|
||||
})
|
||||
.finally(() => void settle())
|
||||
}
|
||||
|
||||
const sendTest = () => {
|
||||
if (testing) return
|
||||
setTesting(true)
|
||||
notificationsApi
|
||||
.testChannel(WEB_PUSH_CHANNEL_ID)
|
||||
.then(result => {
|
||||
if (result.success) toast.success(t('settings.notificationPreferences.testSuccess'))
|
||||
else toast.error(result.error || t('settings.notificationPreferences.testFailed'))
|
||||
})
|
||||
.catch(() => toast.error(t('settings.notificationPreferences.testFailed')))
|
||||
.finally(() => {
|
||||
if (mounted.current) setTesting(false)
|
||||
})
|
||||
}
|
||||
|
||||
const textKey = state ? STATE_TEXT_KEYS[state] : undefined
|
||||
return {
|
||||
state,
|
||||
stateText: textKey ? t(textKey) : null,
|
||||
canSwitch: state === 'on' || state === 'off',
|
||||
on: state === 'on',
|
||||
switchLabel: state === 'on' ? t('settings.webPush.disable') : t('settings.webPush.enable'),
|
||||
busy,
|
||||
canTest: state === 'on' && !testing && !busy,
|
||||
toggle,
|
||||
sendTest,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { authApi, notificationsApi } from '../../../api/client'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import { SWITCH_ONLY_CHANNELS, useNotificationChannels } from '../../../components/Admin/useNotificationChannels'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import MAdminNotifyMatrix from './MAdminNotifyMatrix'
|
||||
import { MAdminButton, MAdminCard, MAdminCardHead, MAdminField, MAdminInput, MAdminRow } from './MAdminUi'
|
||||
@@ -18,39 +19,18 @@ const SMTP_FIELDS = [
|
||||
{ key: 'smtp_from', label: 'From Address', placeholder: 'trek@example.com' },
|
||||
]
|
||||
|
||||
// Notifications section: channel toggles (email/webhook/ntfy/in-app), SMTP
|
||||
// credentials, trip reminders, admin webhook + ntfy targets and the per-event
|
||||
// preference matrix — the desktop notifications tab in mobile cards.
|
||||
// Notifications section: channel toggles (email/webhook/ntfy/web push/in-app),
|
||||
// SMTP credentials, trip reminders, admin webhook + ntfy targets and the
|
||||
// per-event preference matrix: the desktop notifications tab in mobile cards.
|
||||
// The channel switches come from useNotificationChannels, shared with desktop.
|
||||
export default function MAdminNotificationsSection({ admin, t }: MAdminNotificationsSectionProps) {
|
||||
const { toast, smtpValues, setSmtpValues, smtpLoaded, setTripRemindersEnabled } = admin
|
||||
|
||||
// Derive active channels from notification_channels (plural) with fallback
|
||||
// to notification_channel (singular) for existing installs.
|
||||
const rawChannels = smtpValues.notification_channels ?? smtpValues.notification_channel ?? 'none'
|
||||
const activeChans = rawChannels === 'none' ? [] : rawChannels.split(',').map((c: string) => c.trim())
|
||||
const emailActive = activeChans.includes('email')
|
||||
const webhookActive = activeChans.includes('webhook')
|
||||
const ntfyActive = activeChans.includes('ntfy')
|
||||
const channels = useNotificationChannels(admin, t)
|
||||
const emailActive = channels.isActive('email')
|
||||
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
|
||||
const smtpConfigured = !!smtpValues.smtp_host?.trim()
|
||||
|
||||
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
|
||||
// Preserve channel ids this toggle doesn't know about instead of
|
||||
// rebuilding the CSV from just these three booleans.
|
||||
const others = activeChans.filter((c: string) => c !== 'email' && c !== 'webhook' && c !== 'ntfy')
|
||||
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
|
||||
setSmtpValues((prev) => ({ ...prev, notification_channels: chans }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notification_channels: chans })
|
||||
} catch {
|
||||
const reverted =
|
||||
[emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy', ...others].filter(Boolean).join(',') ||
|
||||
'none'
|
||||
setSmtpValues((prev) => ({ ...prev, notification_channels: reverted }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const saveSmtp = async () => {
|
||||
// Saves credentials only — channel activation is auto-saved by the toggle.
|
||||
const notifKeys = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify']
|
||||
@@ -179,7 +159,7 @@ export default function MAdminNotificationsSection({ admin, t }: MAdminNotificat
|
||||
<MToggle
|
||||
checked={emailActive}
|
||||
ariaLabel={t('admin.notifications.emailPanel.title')}
|
||||
onChange={() => setChannels(!emailActive, webhookActive, ntfyActive)}
|
||||
onChange={() => channels.toggle('email')}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
@@ -219,35 +199,22 @@ export default function MAdminNotificationsSection({ admin, t }: MAdminNotificat
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Webhook */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.webhookPanel.title')}
|
||||
hint={t('admin.webhook.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={webhookActive}
|
||||
ariaLabel={t('admin.notifications.webhookPanel.title')}
|
||||
onChange={() => setChannels(emailActive, !webhookActive, ntfyActive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Ntfy */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.ntfy')}
|
||||
hint={t('admin.ntfy.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={ntfyActive}
|
||||
ariaLabel={t('admin.notifications.ntfy')}
|
||||
onChange={() => setChannels(emailActive, webhookActive, !ntfyActive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
{/* Webhook, Ntfy and Web Push: a title, a hint and the switch each */}
|
||||
{SWITCH_ONLY_CHANNELS.map((ch) => (
|
||||
<MAdminCard key={ch.id}>
|
||||
<MAdminCardHead
|
||||
title={t(ch.titleKey)}
|
||||
hint={t(ch.hintKey)}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={channels.isActive(ch.id)}
|
||||
ariaLabel={t(ch.titleKey)}
|
||||
onChange={() => channels.toggle(ch.id)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
))}
|
||||
|
||||
{/* In-App (always on) */}
|
||||
<MAdminCard>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Bell, Link2, Send } from 'lucide-react'
|
||||
import { WEB_PUSH_CHANNEL_ID } from '@trek/shared'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { notificationsApi, settingsApi } from '../../../api/client'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { MSetCard, MSetEyebrow, MSetInput, MSetButton, MSetHint } from './MSettingsUi'
|
||||
import MChip from '../../components/MChip'
|
||||
import MWebPushCard from './MWebPushCard'
|
||||
|
||||
interface ChannelDescriptor {
|
||||
id: string
|
||||
@@ -52,8 +54,8 @@ const MASKED = '••••••••'
|
||||
|
||||
/**
|
||||
* "Notifications" section — NotificationsTab parity: webhook + ntfy channel
|
||||
* credentials, plugin channels and the event/channel preference matrix,
|
||||
* rendered as chip rows instead of the desktop grid.
|
||||
* credentials, push on this device, plugin channels and the event/channel
|
||||
* preference matrix, rendered as chip rows instead of the desktop grid.
|
||||
*/
|
||||
export default function MSettingsNotifications() {
|
||||
const { t } = useTranslation()
|
||||
@@ -282,6 +284,8 @@ export default function MSettingsNotifications() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasChannel(WEB_PUSH_CHANNEL_ID) && <MWebPushCard />}
|
||||
|
||||
{pluginChannels.map((ch) => (
|
||||
<div key={ch.id} className="mb-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] p-3">
|
||||
<MSetEyebrow className="mb-1">{channelLabel(ch, t)}</MSetEyebrow>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { BellRing, BellOff, Send } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useWebPush } from '../../../hooks/useWebPush'
|
||||
import { MSetButton, MSetEyebrow, MSetHint } from './MSettingsUi'
|
||||
|
||||
/**
|
||||
* Phone twin of the desktop `WebPushCard`: markup only, over the same
|
||||
* `useWebPush` hook. MSettingsNotifications renders it while the admin has the
|
||||
* push channel switched on.
|
||||
*/
|
||||
export default function MWebPushCard() {
|
||||
const { t } = useTranslation()
|
||||
const push = useWebPush()
|
||||
|
||||
return (
|
||||
<div className="mb-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] p-3">
|
||||
<MSetEyebrow className="mb-1">{t('settings.webPush.title')}</MSetEyebrow>
|
||||
<MSetHint className="mb-2 mt-0">{t('settings.webPush.hint')}</MSetHint>
|
||||
{push.stateText && (
|
||||
<p role="status" className="mb-2 text-[0.75rem] font-semibold text-m-ink">
|
||||
{push.stateText}
|
||||
</p>
|
||||
)}
|
||||
{push.canSwitch && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<MSetButton variant={push.on ? 'ghost' : 'primary'} onClick={push.toggle} disabled={push.busy}>
|
||||
{push.on ? <BellOff size={13} /> : <BellRing size={13} />}
|
||||
{push.switchLabel}
|
||||
</MSetButton>
|
||||
<MSetButton variant="ghost" onClick={push.sendTest} disabled={!push.canTest}>
|
||||
<Send size={13} />
|
||||
{t('settings.notificationPreferences.sendTest')}
|
||||
</MSetButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1441,7 +1441,8 @@ describe('AdminPage', () => {
|
||||
|
||||
// Find the webhook panel heading ('Webhook') — exact match to avoid 'Admin Webhook'
|
||||
const webhookHeading = screen.getByRole('heading', { name: /^webhook$/i });
|
||||
const webhookCard = webhookHeading.closest<HTMLElement>('.bg-white');
|
||||
// The channel switch cards are drawn with theme tokens, so the card is found by its shape.
|
||||
const webhookCard = webhookHeading.closest<HTMLElement>('.rounded-xl');
|
||||
// Find the toggle button in webhook card
|
||||
const webhookToggle = within(webhookCard!).getByRole('button');
|
||||
fireEvent.click(webhookToggle);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-ADMNOT-001 to FE-ADMNOT-043
|
||||
// FE-ADMNOT-001 to FE-ADMNOT-046
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -571,4 +571,47 @@ describe('AdminNotificationsTab', () => {
|
||||
expect(screen.queryByRole('heading', { name: 'Admin Webhook' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('heading', { name: 'Admin Ntfy' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ADMNOT-044: Web Push has its own card after Ntfy, before In-App', () => {
|
||||
renderTab({ smtpValues: { notification_channels: 'email' } });
|
||||
|
||||
const headings = screen.getAllByRole('heading').map(h => h.textContent);
|
||||
expect(headings.indexOf('Web Push')).toBe(headings.indexOf('Ntfy') + 1);
|
||||
expect(headings.indexOf('In-App')).toBe(headings.indexOf('Web Push') + 1);
|
||||
expect(within(card('Web Push')).getByText(/receive notifications on their phones/)).toBeInTheDocument();
|
||||
expect(within(card('Web Push')).getByRole('button', { name: 'Web Push' })).toHaveAttribute('aria-pressed', 'false');
|
||||
});
|
||||
|
||||
it('FE-ADMNOT-045: switching Web Push on adds push to the list and keeps the rest', async () => {
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.put('/api/auth/app-settings', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({});
|
||||
})
|
||||
);
|
||||
const admin = renderTab({ smtpValues: { notification_channels: 'email,plugin-gotify' } });
|
||||
|
||||
fireEvent.click(within(card('Web Push')).getByRole('button', { name: 'Web Push' }));
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ notification_channels: 'email,push,plugin-gotify' }));
|
||||
expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,push,plugin-gotify');
|
||||
});
|
||||
|
||||
it('FE-ADMNOT-046: an active push channel shows its switch on, and switching it off keeps email', async () => {
|
||||
let body: Record<string, unknown> | null = null;
|
||||
server.use(
|
||||
http.put('/api/auth/app-settings', async ({ request }) => {
|
||||
body = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({});
|
||||
})
|
||||
);
|
||||
renderTab({ smtpValues: { notification_channels: 'email,push' } });
|
||||
|
||||
const toggle = within(card('Web Push')).getByRole('button', { name: 'Web Push' });
|
||||
expect(toggle).toHaveAttribute('aria-pressed', 'true');
|
||||
fireEvent.click(toggle);
|
||||
|
||||
await waitFor(() => expect(body).toEqual({ notification_channels: 'email' }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,43 +4,39 @@ import { Save } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import type { useAdmin } from './useAdmin'
|
||||
import AdminNotificationsPanel from './AdminNotificationsPanel'
|
||||
import { SWITCH_ONLY_CHANNELS, useNotificationChannels } from '../../components/Admin/useNotificationChannels'
|
||||
|
||||
interface AdminNotificationsTabProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
// "Notifications" admin tab: email/webhook/ntfy channel toggles, SMTP credentials,
|
||||
// trip reminders, admin webhook + ntfy targets, and the per-event preference matrix.
|
||||
// Derives channel state from smtpValues exactly as the original inline IIFE did.
|
||||
/** The on/off switch at the right of a channel card. */
|
||||
function ChannelSwitch({ on, label, onToggle }: { on: boolean; label: string; onToggle: () => void }): React.ReactElement {
|
||||
return (
|
||||
<button type="button"
|
||||
onClick={onToggle}
|
||||
aria-pressed={on}
|
||||
aria-label={label}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${on ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-surface-card transition-transform duration-200"
|
||||
style={{ transform: on ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// "Notifications" admin tab: email/webhook/ntfy/web push channel toggles, SMTP
|
||||
// credentials, trip reminders, admin webhook + ntfy targets, and the per-event
|
||||
// preference matrix. The channel switches come from useNotificationChannels,
|
||||
// which the phone section shares.
|
||||
export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTabProps): React.ReactElement {
|
||||
const { toast, smtpValues, setSmtpValues, smtpLoaded, setTripRemindersEnabled, managed } = admin
|
||||
|
||||
// Derive active channels from smtpValues.notification_channels (plural)
|
||||
// with fallback to notification_channel (singular) for existing installs
|
||||
const rawChannels = smtpValues.notification_channels ?? smtpValues.notification_channel ?? 'none'
|
||||
const activeChans = rawChannels === 'none' ? [] : rawChannels.split(',').map((c: string) => c.trim())
|
||||
const emailActive = activeChans.includes('email')
|
||||
const webhookActive = activeChans.includes('webhook')
|
||||
const ntfyActive = activeChans.includes('ntfy')
|
||||
const channels = useNotificationChannels(admin, t)
|
||||
const emailActive = channels.isActive('email')
|
||||
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
|
||||
|
||||
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
|
||||
// Preserve any id this toggle doesn't know about instead of rebuilding the CSV from
|
||||
// just these three booleans — that used to silently DROP anything else stored here.
|
||||
const others = activeChans.filter((c: string) => c !== 'email' && c !== 'webhook' && c !== 'ntfy')
|
||||
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: chans }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notification_channels: chans })
|
||||
} catch {
|
||||
// Revert state on failure
|
||||
const reverted = [emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
|
||||
setSmtpValues(prev => ({ ...prev, notification_channels: reverted }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const smtpConfigured = !!(smtpValues.smtp_host?.trim())
|
||||
const saveNotifications = async () => {
|
||||
// Saves credentials only — channel activation is auto-saved by the toggle
|
||||
@@ -64,7 +60,7 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
|
||||
pairs cards row by row and leaves a hole under the shorter one, and the SMTP
|
||||
card is taller than all the toggle rows together. Grouped by audience, not by
|
||||
height — the channels a user can receive on the left, everything the operator
|
||||
sends or receives themselves on the right. The three channel switches stay
|
||||
sends or receives themselves on the right. The channel switches stay
|
||||
together because they all write the same notification_channels list.
|
||||
On a managed install the two admin-target cards are gone and the right column
|
||||
is the matrix alone — still a column, so the grid keeps working. */}
|
||||
@@ -81,13 +77,7 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.emailPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.smtp.hint')}</p>
|
||||
</div>
|
||||
<button type="button"
|
||||
onClick={() => setChannels(!emailActive, webhookActive, ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${emailActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: emailActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
<ChannelSwitch on={emailActive} label={t('admin.notifications.emailPanel.title')} onToggle={() => channels.toggle('email')} />
|
||||
</div>
|
||||
<div className={`p-6 space-y-3 ${!emailActive ? 'opacity-50 pointer-events-none' : ''}`}>
|
||||
{smtpLoaded && [
|
||||
@@ -152,39 +142,18 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
|
||||
</div>
|
||||
|
||||
</>)}
|
||||
{/* Webhook Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.webhookPanel.title')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.webhook.hint')}</p>
|
||||
{/* Webhook, Ntfy and Web Push: a title, a hint and the switch each */}
|
||||
{SWITCH_ONLY_CHANNELS.map(ch => (
|
||||
<div key={ch.id} className="bg-surface-card rounded-xl border border-edge overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-content">{t(ch.titleKey)}</h2>
|
||||
<p className="text-caption text-content-faint mt-1">{t(ch.hintKey)}</p>
|
||||
</div>
|
||||
<ChannelSwitch on={channels.isActive(ch.id)} label={t(ch.titleKey)} onToggle={() => channels.toggle(ch.id)} />
|
||||
</div>
|
||||
<button type="button"
|
||||
onClick={() => setChannels(emailActive, !webhookActive, ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${webhookActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: webhookActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ntfy Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<div className="px-6 py-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">{t('admin.notifications.ntfy')}</h2>
|
||||
<p className="text-xs text-slate-400 mt-1">{t('admin.ntfy.hint') || 'Allow users to configure their own ntfy topics for push notifications.'}</p>
|
||||
</div>
|
||||
<button type="button"
|
||||
onClick={() => setChannels(emailActive, webhookActive, !ntfyActive)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${ntfyActive ? 'bg-content' : 'bg-edge'}`}
|
||||
>
|
||||
<span className="absolute left-0.5 h-5 w-5 rounded-full bg-white transition-transform duration-200"
|
||||
style={{ transform: ntfyActive ? 'translateX(20px)' : 'translateX(0)' }} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* In-App Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
/**
|
||||
* FE-PUSH-001 to FE-PUSH-044: this device's Web Push, against a fake browser.
|
||||
*
|
||||
* jsdom has no service worker, no PushManager and no Notification, so every
|
||||
* case installs the three by hand. What is worth pinning here:
|
||||
*
|
||||
* 1. **Support is a reason, not a yes/no.** An insecure origin, an iPhone in
|
||||
* a Safari tab and a browser without push each need a different sentence,
|
||||
* because each has a different fix.
|
||||
* 2. **The gesture.** WebKit honours the permission prompt only inside the
|
||||
* click, so `enableWebPush` must ask before its first await.
|
||||
* 3. **The browser is the record.** A subscription the server refused is
|
||||
* rolled back, switching off unsubscribes even when the server cannot be
|
||||
* told, and logout forgets the device before the cookie goes, bounded so it
|
||||
* can never hang, and with a plain fetch so a 401 cannot redirect.
|
||||
* 4. **The re-sync after sign-in** repeats what the device holds, replaces a
|
||||
* subscription made with an old server key, and never calls update().
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
getPublicKey: vi.fn(),
|
||||
subscribe: vi.fn(),
|
||||
unsubscribe: vi.fn(),
|
||||
}))
|
||||
vi.mock('../api/push', () => ({ pushApi: api }))
|
||||
|
||||
const network = vi.hoisted(() => ({ offline: false }))
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline }))
|
||||
|
||||
import {
|
||||
base64UrlToUint8Array,
|
||||
currentPushSubscription,
|
||||
disableWebPush,
|
||||
enableWebPush,
|
||||
forgetPushDeviceOnLogout,
|
||||
getPushPermission,
|
||||
getWebPushSupport,
|
||||
loadPushPublicKey,
|
||||
readWebPushDeviceState,
|
||||
resyncPushSubscription,
|
||||
toSubscriptionInput,
|
||||
waitForPushRegistration,
|
||||
WebPushError,
|
||||
} from './webPush'
|
||||
|
||||
/** A P-256 point is 65 bytes; these tests only need two keys that differ. */
|
||||
const SERVER_KEY = 'BAECAwQ'
|
||||
const OTHER_KEY = 'BAUGBwg'
|
||||
|
||||
class FakeSubscription {
|
||||
readonly options: { applicationServerKey: ArrayBuffer | null; userVisibleOnly: boolean }
|
||||
unsubscribe = vi.fn(async () => true)
|
||||
|
||||
constructor(
|
||||
readonly endpoint: string,
|
||||
key: Uint8Array | null,
|
||||
) {
|
||||
this.options = { applicationServerKey: key ? new Uint8Array(key).buffer : null, userVisibleOnly: true }
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return { endpoint: this.endpoint, expirationTime: null, keys: { p256dh: 'p256-' + this.endpoint, auth: 'auth' } }
|
||||
}
|
||||
}
|
||||
|
||||
class FakePushManager {
|
||||
current: FakeSubscription | null = null
|
||||
created = 0
|
||||
subscribe = vi.fn(async (options: { userVisibleOnly?: boolean; applicationServerKey: Uint8Array }) => {
|
||||
this.created++
|
||||
this.current = new FakeSubscription(`https://push.example/sub-${this.created}`, options.applicationServerKey)
|
||||
return this.current
|
||||
})
|
||||
getSubscription = vi.fn(async () => this.current)
|
||||
}
|
||||
|
||||
interface Browser {
|
||||
pushManager: FakePushManager
|
||||
registration: { pushManager: FakePushManager; update: ReturnType<typeof vi.fn> }
|
||||
container: { getRegistration: ReturnType<typeof vi.fn>; ready: Promise<unknown> }
|
||||
notification: { permission: NotificationPermission; requestPermission: ReturnType<typeof vi.fn> }
|
||||
}
|
||||
|
||||
function installBrowser(opts: { permission?: NotificationPermission; answer?: NotificationPermission } = {}): Browser {
|
||||
const pushManager = new FakePushManager()
|
||||
const registration = { pushManager, update: vi.fn() }
|
||||
const container = { getRegistration: vi.fn(async () => registration), ready: Promise.resolve(registration) }
|
||||
Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: container })
|
||||
const notification = {
|
||||
permission: opts.permission ?? 'default',
|
||||
requestPermission: vi.fn(async () => {
|
||||
notification.permission = opts.answer ?? 'granted'
|
||||
return notification.permission
|
||||
}),
|
||||
}
|
||||
vi.stubGlobal('Notification', notification)
|
||||
vi.stubGlobal('PushManager', function PushManager() {})
|
||||
vi.stubGlobal('isSecureContext', true)
|
||||
return { pushManager, registration, container, notification }
|
||||
}
|
||||
|
||||
function subscribed(browser: Browser, key = SERVER_KEY, endpoint = 'https://push.example/existing') {
|
||||
browser.pushManager.current = new FakeSubscription(endpoint, base64UrlToUint8Array(key))
|
||||
return browser.pushManager.current
|
||||
}
|
||||
|
||||
/** Own properties shadow jsdom's prototype getters; afterEach deletes them again. */
|
||||
function setUserAgent(ua: string, touchPoints = 0) {
|
||||
Object.defineProperty(navigator, 'userAgent', { configurable: true, get: () => ua })
|
||||
Object.defineProperty(navigator, 'maxTouchPoints', { configurable: true, get: () => touchPoints })
|
||||
}
|
||||
|
||||
const IPHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile Safari/604.1'
|
||||
const IPAD_DESKTOP = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15'
|
||||
const CHROME = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/140.0 Safari/537.36'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
network.offline = false
|
||||
api.getPublicKey.mockResolvedValue({ publicKey: SERVER_KEY })
|
||||
api.subscribe.mockResolvedValue({ success: true, devices: 1 })
|
||||
api.unsubscribe.mockResolvedValue({ success: true })
|
||||
setUserAgent(CHROME)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
delete (navigator as unknown as { serviceWorker?: unknown }).serviceWorker
|
||||
delete (navigator as unknown as { standalone?: unknown }).standalone
|
||||
delete (navigator as unknown as { userAgent?: unknown }).userAgent
|
||||
delete (navigator as unknown as { maxTouchPoints?: unknown }).maxTouchPoints
|
||||
})
|
||||
|
||||
describe('getWebPushSupport', () => {
|
||||
it('FE-PUSH-001: a secure browser with a worker, PushManager and Notification is supported', () => {
|
||||
installBrowser()
|
||||
expect(getWebPushSupport()).toEqual({ supported: true, reason: null })
|
||||
})
|
||||
|
||||
it('FE-PUSH-002: an insecure origin says so before anything else', () => {
|
||||
installBrowser()
|
||||
vi.stubGlobal('isSecureContext', false)
|
||||
setUserAgent(IPHONE)
|
||||
expect(getWebPushSupport()).toEqual({ supported: false, reason: 'insecure' })
|
||||
})
|
||||
|
||||
it('FE-PUSH-003: an iPhone in a Safari tab is told to add TREK to the Home Screen', () => {
|
||||
vi.stubGlobal('isSecureContext', true)
|
||||
setUserAgent(IPHONE, 5)
|
||||
expect(getWebPushSupport()).toEqual({ supported: false, reason: 'ios-install' })
|
||||
})
|
||||
|
||||
it('FE-PUSH-004: an iPad asking for the desktop site counts as iOS too', () => {
|
||||
installBrowser()
|
||||
setUserAgent(IPAD_DESKTOP, 5)
|
||||
expect(getWebPushSupport().reason).toBe('ios-install')
|
||||
})
|
||||
|
||||
it('FE-PUSH-005: a real Mac (no touch screen) is not mistaken for an iPad', () => {
|
||||
installBrowser()
|
||||
setUserAgent(IPAD_DESKTOP, 0)
|
||||
expect(getWebPushSupport().supported).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-PUSH-006: the installed iOS app is supported', () => {
|
||||
installBrowser()
|
||||
setUserAgent(IPHONE, 5)
|
||||
Object.defineProperty(navigator, 'standalone', { configurable: true, value: true })
|
||||
expect(getWebPushSupport().supported).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-PUSH-007: the installed app on an iOS without push still reads as unsupported', () => {
|
||||
vi.stubGlobal('isSecureContext', true)
|
||||
setUserAgent(IPHONE, 5)
|
||||
Object.defineProperty(navigator, 'standalone', { configurable: true, value: true })
|
||||
expect(getWebPushSupport()).toEqual({ supported: false, reason: 'unsupported' })
|
||||
})
|
||||
|
||||
it('FE-PUSH-008: a desktop browser without the APIs is unsupported', () => {
|
||||
vi.stubGlobal('isSecureContext', true)
|
||||
expect(getWebPushSupport()).toEqual({ supported: false, reason: 'unsupported' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('small helpers', () => {
|
||||
it('FE-PUSH-009: the permission falls back to default where Notification is missing', () => {
|
||||
expect(getPushPermission()).toBe('default')
|
||||
installBrowser({ permission: 'denied' })
|
||||
expect(getPushPermission()).toBe('denied')
|
||||
})
|
||||
|
||||
it('FE-PUSH-010: base64url keys decode to their raw bytes, padding or not', () => {
|
||||
expect(Array.from(base64UrlToUint8Array('AQID'))).toEqual([1, 2, 3])
|
||||
expect(Array.from(base64UrlToUint8Array('-_8'))).toEqual([251, 255])
|
||||
expect(Array.from(base64UrlToUint8Array('-_8='))).toEqual([251, 255])
|
||||
})
|
||||
|
||||
it('FE-PUSH-011: a subscription becomes the shared contract shape', () => {
|
||||
const sub = new FakeSubscription('https://push.example/a', null)
|
||||
expect(toSubscriptionInput(sub as unknown as PushSubscription)).toEqual({
|
||||
endpoint: 'https://push.example/a',
|
||||
expirationTime: null,
|
||||
keys: { p256dh: 'p256-https://push.example/a', auth: 'auth' },
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-PUSH-012: a subscription without keys is refused rather than sent half', () => {
|
||||
const broken = { toJSON: () => ({ endpoint: 'https://push.example/a', keys: {} }) }
|
||||
expect(() => toSubscriptionInput(broken as unknown as PushSubscription)).toThrow(WebPushError)
|
||||
})
|
||||
|
||||
it('FE-PUSH-013: the public key loads, and a failure is null rather than a rejection', async () => {
|
||||
await expect(loadPushPublicKey()).resolves.toBe(SERVER_KEY)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
api.getPublicKey.mockRejectedValueOnce(new Error('offline'))
|
||||
await expect(loadPushPublicKey()).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('FE-PUSH-014: there is no subscription to read without the APIs or a registration', async () => {
|
||||
await expect(currentPushSubscription()).resolves.toBeNull()
|
||||
const browser = installBrowser()
|
||||
browser.container.getRegistration.mockResolvedValueOnce(undefined)
|
||||
await expect(currentPushSubscription()).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('waitForPushRegistration', () => {
|
||||
it('FE-PUSH-015: hands over the active registration', async () => {
|
||||
const browser = installBrowser()
|
||||
await expect(waitForPushRegistration()).resolves.toBe(browser.registration)
|
||||
})
|
||||
|
||||
it('FE-PUSH-016: gives up after the timeout on a page that never gets a worker', async () => {
|
||||
const browser = installBrowser()
|
||||
browser.container.ready = new Promise(() => {})
|
||||
vi.useFakeTimers()
|
||||
const waiting = waitForPushRegistration(1000)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await expect(waiting).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('FE-PUSH-017: is null straight away where the APIs are missing', async () => {
|
||||
await expect(waitForPushRegistration()).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('readWebPushDeviceState', () => {
|
||||
it('FE-PUSH-018: an unsupported browser reports its reason', async () => {
|
||||
vi.stubGlobal('isSecureContext', false)
|
||||
await expect(readWebPushDeviceState()).resolves.toBe('insecure')
|
||||
})
|
||||
|
||||
it('FE-PUSH-019: a blocked permission wins over an old subscription', async () => {
|
||||
const browser = installBrowser({ permission: 'denied' })
|
||||
subscribed(browser)
|
||||
await expect(readWebPushDeviceState()).resolves.toBe('denied')
|
||||
})
|
||||
|
||||
it('FE-PUSH-020: on with a subscription, off without', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
await expect(readWebPushDeviceState()).resolves.toBe('off')
|
||||
subscribed(browser)
|
||||
await expect(readWebPushDeviceState()).resolves.toBe('on')
|
||||
})
|
||||
|
||||
it('FE-PUSH-021: a registration that cannot be read counts as off, not as an error', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
browser.container.getRegistration.mockRejectedValueOnce(new Error('site data blocked'))
|
||||
await expect(readWebPushDeviceState()).resolves.toBe('off')
|
||||
})
|
||||
})
|
||||
|
||||
describe('enableWebPush', () => {
|
||||
it('FE-PUSH-022: asks for permission before its first await, so the gesture still counts', async () => {
|
||||
const browser = installBrowser()
|
||||
const done = enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)
|
||||
expect(browser.notification.requestPermission).toHaveBeenCalledTimes(1)
|
||||
await done
|
||||
})
|
||||
|
||||
it('FE-PUSH-023: subscribes visibly with the server key and registers the device', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
await enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)
|
||||
|
||||
expect(browser.notification.requestPermission).not.toHaveBeenCalled()
|
||||
const options = browser.pushManager.subscribe.mock.calls[0][0]
|
||||
expect(options.userVisibleOnly).toBe(true)
|
||||
expect(Array.from(options.applicationServerKey)).toEqual(Array.from(base64UrlToUint8Array(SERVER_KEY)))
|
||||
expect(api.subscribe).toHaveBeenCalledWith(toSubscriptionInput(browser.pushManager.current as unknown as PushSubscription))
|
||||
})
|
||||
|
||||
it('FE-PUSH-024: waits for the worker when no registration was handed over', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
await enableWebPush(SERVER_KEY)
|
||||
expect(browser.pushManager.subscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-PUSH-025: a block is reported as denied and nothing is subscribed', async () => {
|
||||
const browser = installBrowser({ answer: 'denied' })
|
||||
await expect(enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)).rejects.toMatchObject({ code: 'denied' })
|
||||
expect(browser.pushManager.subscribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-026: a prompt closed without an answer is dismissed, not a failure', async () => {
|
||||
const browser = installBrowser({ answer: 'default' })
|
||||
await expect(enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)).rejects.toMatchObject({ code: 'dismissed' })
|
||||
})
|
||||
|
||||
it('FE-PUSH-027: without a worker it fails instead of spinning', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
browser.container.ready = new Promise(() => {})
|
||||
vi.useFakeTimers()
|
||||
const done = enableWebPush(SERVER_KEY).catch(err => err)
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(await done).toMatchObject({ code: 'failed' })
|
||||
})
|
||||
|
||||
it('FE-PUSH-028: a subscription left over from an older server key is replaced', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const stale = subscribed(browser, OTHER_KEY, 'https://push.example/stale')
|
||||
browser.pushManager.subscribe.mockRejectedValueOnce(new DOMException('key mismatch', 'InvalidStateError'))
|
||||
|
||||
await enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)
|
||||
|
||||
expect(api.unsubscribe).toHaveBeenCalledWith('https://push.example/stale')
|
||||
expect(stale.unsubscribe).toHaveBeenCalled()
|
||||
expect(browser.pushManager.subscribe).toHaveBeenCalledTimes(2)
|
||||
expect(api.subscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-PUSH-029: any other subscribe failure is final', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
browser.pushManager.subscribe.mockRejectedValueOnce(new DOMException('push service down', 'AbortError'))
|
||||
await expect(enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)).rejects.toMatchObject({ code: 'failed' })
|
||||
expect(browser.pushManager.subscribe).toHaveBeenCalledTimes(1)
|
||||
expect(api.subscribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-030: a subscription the server refused is rolled back in the browser', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
api.subscribe.mockRejectedValueOnce(new Error('400'))
|
||||
await expect(enableWebPush(SERVER_KEY, browser.registration as unknown as ServiceWorkerRegistration)).rejects.toMatchObject({ code: 'failed' })
|
||||
expect(browser.pushManager.current?.unsubscribe).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('disableWebPush', () => {
|
||||
it('FE-PUSH-031: forgets the device on the server, then unsubscribes the browser', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
const order: string[] = []
|
||||
api.unsubscribe.mockImplementationOnce(async () => {
|
||||
order.push('server')
|
||||
return { success: true }
|
||||
})
|
||||
sub.unsubscribe.mockImplementationOnce(async () => {
|
||||
order.push('browser')
|
||||
return true
|
||||
})
|
||||
|
||||
await disableWebPush()
|
||||
|
||||
expect(api.unsubscribe).toHaveBeenCalledWith('https://push.example/existing')
|
||||
expect(order).toEqual(['server', 'browser'])
|
||||
})
|
||||
|
||||
it('FE-PUSH-032: still unsubscribes when the server cannot be told', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
api.unsubscribe.mockRejectedValueOnce(new Error('offline'))
|
||||
await disableWebPush()
|
||||
expect(sub.unsubscribe).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-033: does nothing without a subscription, and reports a browser that refuses', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
await disableWebPush()
|
||||
expect(api.unsubscribe).not.toHaveBeenCalled()
|
||||
|
||||
const sub = subscribed(browser)
|
||||
sub.unsubscribe.mockRejectedValueOnce(new Error('refused'))
|
||||
await expect(disableWebPush()).rejects.toThrow('refused')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resyncPushSubscription', () => {
|
||||
it('FE-PUSH-034: stays quiet when push is unsupported, not granted or the app is offline', async () => {
|
||||
await resyncPushSubscription()
|
||||
const browser = installBrowser({ permission: 'default' })
|
||||
subscribed(browser)
|
||||
await resyncPushSubscription()
|
||||
browser.notification.permission = 'granted'
|
||||
network.offline = true
|
||||
await resyncPushSubscription()
|
||||
expect(browser.container.getRegistration).not.toHaveBeenCalled()
|
||||
expect(api.subscribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-035: registers the subscription the device holds again, without update()', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
await resyncPushSubscription()
|
||||
expect(api.subscribe).toHaveBeenCalledWith(toSubscriptionInput(sub as unknown as PushSubscription))
|
||||
expect(browser.pushManager.subscribe).not.toHaveBeenCalled()
|
||||
expect(browser.registration.update).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-036: does nothing for a device that never switched push on', async () => {
|
||||
installBrowser({ permission: 'granted' })
|
||||
await resyncPushSubscription()
|
||||
expect(api.getPublicKey).not.toHaveBeenCalled()
|
||||
expect(api.subscribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-037: replaces a subscription made with an old server key', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const stale = subscribed(browser, OTHER_KEY, 'https://push.example/stale')
|
||||
await resyncPushSubscription()
|
||||
expect(api.unsubscribe).toHaveBeenCalledWith('https://push.example/stale')
|
||||
expect(stale.unsubscribe).toHaveBeenCalled()
|
||||
expect(browser.pushManager.subscribe).toHaveBeenCalledTimes(1)
|
||||
expect(api.subscribe).toHaveBeenCalledWith(expect.objectContaining({ endpoint: 'https://push.example/sub-1' }))
|
||||
})
|
||||
|
||||
it('FE-PUSH-038: a browser that does not report its key is taken at its word', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
browser.pushManager.current = new FakeSubscription('https://push.example/unknown-key', null)
|
||||
await resyncPushSubscription()
|
||||
expect(browser.pushManager.subscribe).not.toHaveBeenCalled()
|
||||
expect(api.subscribe).toHaveBeenCalledWith(expect.objectContaining({ endpoint: 'https://push.example/unknown-key' }))
|
||||
})
|
||||
|
||||
it('FE-PUSH-039: never rejects, even when the server does', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
subscribed(browser)
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
api.subscribe.mockRejectedValueOnce(new Error('500'))
|
||||
await expect(resyncPushSubscription()).resolves.toBeUndefined()
|
||||
expect(warn).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgetPushDeviceOnLogout', () => {
|
||||
/** The logout DELETE is a plain fetch, so a 401 can never reach apiClient's login redirect. */
|
||||
function stubFetch(answer: (init?: RequestInit) => Promise<Response>) {
|
||||
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => answer(init))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
return fetchMock
|
||||
}
|
||||
|
||||
it('FE-PUSH-040: forgets the device on the server with a plain fetch, and in the browser', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
const fetchMock = stubFetch(async () => Response.json({ success: true }))
|
||||
|
||||
await forgetPushDeviceOnLogout()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('/api/notifications/push/subscriptions')
|
||||
expect(init).toMatchObject({
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
expect(JSON.parse(String(init?.body))).toEqual({ endpoint: 'https://push.example/existing' })
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal)
|
||||
expect(api.unsubscribe).not.toHaveBeenCalled()
|
||||
expect(sub.unsubscribe).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-041: returns at once where there is no push at all', async () => {
|
||||
const fetchMock = stubFetch(async () => Response.json({ success: true }))
|
||||
await forgetPushDeviceOnLogout()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(api.unsubscribe).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-PUSH-042: a server that never answers cannot hold the logout up or keep the browser subscribed', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
// Like a real fetch to a server that never answers: it settles only once its signal aborts.
|
||||
const fetchMock = stubFetch(
|
||||
init =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))
|
||||
}),
|
||||
)
|
||||
vi.useFakeTimers()
|
||||
let finished = false
|
||||
const done = forgetPushDeviceOnLogout(3000).then(() => {
|
||||
finished = true
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(2999)
|
||||
expect(finished).toBe(false)
|
||||
expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(false)
|
||||
// The browser half never waited for the server half.
|
||||
expect(sub.unsubscribe).toHaveBeenCalledTimes(1)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
await done
|
||||
expect(finished).toBe(true)
|
||||
expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true)
|
||||
expect(warn).toHaveBeenCalledWith('[push] forgetting the device on the server failed', expect.any(DOMException))
|
||||
})
|
||||
|
||||
it('FE-PUSH-043: a 401 from a session that already ran out neither redirects nor stops the browser half', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const before = window.location.href
|
||||
stubFetch(async () => Response.json({ error: 'Authentication required', code: 'AUTH_REQUIRED' }, { status: 401 }))
|
||||
|
||||
await expect(forgetPushDeviceOnLogout()).resolves.toBeUndefined()
|
||||
|
||||
expect(window.location.href).toBe(before)
|
||||
expect(api.unsubscribe).not.toHaveBeenCalled()
|
||||
expect(sub.unsubscribe).toHaveBeenCalled()
|
||||
expect(warn).toHaveBeenCalledWith('[push] forgetting the device on the server failed', expect.any(Error))
|
||||
})
|
||||
|
||||
it('FE-PUSH-044: a network failure on the server half still unsubscribes the browser', async () => {
|
||||
const browser = installBrowser({ permission: 'granted' })
|
||||
const sub = subscribed(browser)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
stubFetch(() => Promise.reject(new TypeError('Failed to fetch')))
|
||||
await forgetPushDeviceOnLogout()
|
||||
expect(sub.unsubscribe).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,338 @@
|
||||
import type { PushSubscriptionInput, PushUnsubscribeRequest } from '@trek/shared'
|
||||
import { pushApi } from '../api/push'
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import { isIosDevice, isIosStandalone } from '../utils/iosDevice'
|
||||
|
||||
/**
|
||||
* Web Push on this device: whether it can work here, and switching it on and
|
||||
* off.
|
||||
*
|
||||
* Deliberately online only, and deliberately without a mirror. The browser's
|
||||
* push subscription is the one record of "this device receives push"; the
|
||||
* server keeps its copy keyed by the subscription's endpoint, and nothing in
|
||||
* Zustand or Dexie repeats either. Making a subscription needs the browser's
|
||||
* push service and the server at the same moment, so an offline queue would
|
||||
* have nothing to replay, and a cached copy could only ever disagree with the
|
||||
* browser.
|
||||
*
|
||||
* React-free on purpose: the settings cards (through `useWebPush`), the auth
|
||||
* store (logout and the re-sync after sign-in) and the tests all drive these
|
||||
* same functions.
|
||||
*/
|
||||
|
||||
export type WebPushUnsupportedReason = 'insecure' | 'unsupported' | 'ios-install'
|
||||
|
||||
/** `reason` is null exactly when `supported` is true. */
|
||||
export interface WebPushSupport {
|
||||
supported: boolean
|
||||
reason: WebPushUnsupportedReason | null
|
||||
}
|
||||
|
||||
/** What the settings card has to say about this device. */
|
||||
export type WebPushDeviceState = WebPushUnsupportedReason | 'denied' | 'off' | 'on'
|
||||
|
||||
export type WebPushErrorCode = 'denied' | 'dismissed' | 'failed'
|
||||
|
||||
/** Why switching push on did not work: blocked, the prompt closed without an answer, or anything else. */
|
||||
export class WebPushError extends Error {
|
||||
readonly code: WebPushErrorCode
|
||||
readonly reason: unknown
|
||||
|
||||
constructor(code: WebPushErrorCode, reason?: unknown) {
|
||||
super(`Web Push: ${code}`)
|
||||
this.name = 'WebPushError'
|
||||
this.code = code
|
||||
this.reason = reason
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How long switching push on waits for the service worker. `registerSW.js`
|
||||
* installs it on page load, so this only runs out on a page that never got
|
||||
* one, and there the card should say so rather than spin.
|
||||
*/
|
||||
export const REGISTRATION_TIMEOUT_MS = 10_000
|
||||
|
||||
/** Logout waits at most this long for this device to be forgotten. It must never hang on it. */
|
||||
export const LOGOUT_PUSH_TIMEOUT_MS = 3_000
|
||||
|
||||
function hasPushApis(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof navigator !== 'undefined' &&
|
||||
'serviceWorker' in navigator &&
|
||||
'PushManager' in window &&
|
||||
'Notification' in window
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether push can work in this browser, and if not, the reason the user can
|
||||
* do something about.
|
||||
*/
|
||||
export function getWebPushSupport(): WebPushSupport {
|
||||
if (typeof window === 'undefined') return unsupported('unsupported')
|
||||
// A service worker, and push with it, exists only in a secure context: HTTPS,
|
||||
// or localhost while developing. A plain http LAN address never gets one.
|
||||
if (window.isSecureContext === false) return unsupported('insecure')
|
||||
// iOS and iPadOS deliver push only to TREK added to the Home Screen. In a
|
||||
// Safari tab the APIs are simply missing, which would read as "this browser
|
||||
// cannot" when the fix is one tap in the share menu.
|
||||
if (isIosDevice() && !isIosStandalone()) return unsupported('ios-install')
|
||||
if (!hasPushApis()) return unsupported('unsupported')
|
||||
return { supported: true, reason: null }
|
||||
}
|
||||
|
||||
function unsupported(reason: WebPushUnsupportedReason): WebPushSupport {
|
||||
return { supported: false, reason }
|
||||
}
|
||||
|
||||
/** The notification permission as the browser holds it right now. */
|
||||
export function getPushPermission(): NotificationPermission {
|
||||
return typeof window !== 'undefined' && 'Notification' in window ? Notification.permission : 'default'
|
||||
}
|
||||
|
||||
/** The applicationServerKey the browser wants: the raw bytes behind the server's base64url string. */
|
||||
export function base64UrlToUint8Array(value: string): Uint8Array<ArrayBuffer> {
|
||||
const base64 = value.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=')
|
||||
return Uint8Array.from(atob(padded), ch => ch.codePointAt(0) ?? 0)
|
||||
}
|
||||
|
||||
/** A key the browser reports it subscribed with, compared with the server's. Unknown counts as the same. */
|
||||
function keyMatches(subscribedWith: ArrayBuffer | null | undefined, serverKey: Uint8Array): boolean {
|
||||
if (!subscribedWith) return true
|
||||
const bytes = new Uint8Array(subscribedWith)
|
||||
return bytes.length === serverKey.length && bytes.every((byte, i) => byte === serverKey[i])
|
||||
}
|
||||
|
||||
/** What `PushSubscription.toJSON()` hands over, in the shape of the shared contract. */
|
||||
export function toSubscriptionInput(subscription: PushSubscription): PushSubscriptionInput {
|
||||
const json = subscription.toJSON()
|
||||
const p256dh = json.keys?.p256dh
|
||||
const auth = json.keys?.auth
|
||||
if (!json.endpoint || !p256dh || !auth) throw new WebPushError('failed', 'subscription without keys')
|
||||
return { endpoint: json.endpoint, expirationTime: json.expirationTime ?? null, keys: { p256dh, auth } }
|
||||
}
|
||||
|
||||
/** Settles with `fallback` once `ms` have passed, unless `promise` settled first. */
|
||||
function withTimeout<T, F>(promise: Promise<T>, ms: number, fallback: F): Promise<T | F> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timeout = new Promise<F>(resolve => {
|
||||
timer = setTimeout(() => resolve(fallback), ms)
|
||||
})
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
/**
|
||||
* A step whose failure changes nothing for the caller. It still gets a line in
|
||||
* the console, because "push quietly stopped" is otherwise impossible to trace.
|
||||
*/
|
||||
async function bestEffort<T>(what: string, step: () => Promise<T>): Promise<T | undefined> {
|
||||
try {
|
||||
return await step()
|
||||
} catch (err) {
|
||||
console.warn(`[push] ${what} failed`, err)
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The registration already in charge of this origin, or null. It neither waits
|
||||
* for one to appear nor calls update(): the version handover owns updates, and
|
||||
* its tests count every call.
|
||||
*/
|
||||
async function existingRegistration(): Promise<ServiceWorkerRegistration | null> {
|
||||
const container = navigator.serviceWorker
|
||||
if (!container || typeof container.getRegistration !== 'function') return null
|
||||
return (await container.getRegistration()) ?? null
|
||||
}
|
||||
|
||||
/** This device's subscription, or null when it has none or cannot have one. */
|
||||
export async function currentPushSubscription(): Promise<PushSubscription | null> {
|
||||
if (!hasPushApis()) return null
|
||||
const registration = await existingRegistration()
|
||||
if (!registration?.pushManager) return null
|
||||
return registration.pushManager.getSubscription()
|
||||
}
|
||||
|
||||
/**
|
||||
* The active registration, for subscribing. `ready` never settles on a page
|
||||
* without a service worker, hence the timeout.
|
||||
*/
|
||||
export async function waitForPushRegistration(
|
||||
timeoutMs = REGISTRATION_TIMEOUT_MS,
|
||||
): Promise<ServiceWorkerRegistration | null> {
|
||||
if (!hasPushApis()) return null
|
||||
return withTimeout(navigator.serviceWorker.ready, timeoutMs, null)
|
||||
}
|
||||
|
||||
/** The server's public key, or null when it could not be fetched now. Never rejects. */
|
||||
export async function loadPushPublicKey(): Promise<string | null> {
|
||||
const result = await bestEffort('loading the public key', () => pushApi.getPublicKey())
|
||||
return result?.publicKey || null
|
||||
}
|
||||
|
||||
/** What the settings card shows for this device. Never rejects. */
|
||||
export async function readWebPushDeviceState(): Promise<WebPushDeviceState> {
|
||||
const { reason } = getWebPushSupport()
|
||||
if (reason) return reason
|
||||
if (getPushPermission() === 'denied') return 'denied'
|
||||
const subscription = await bestEffort('reading the subscription', () => currentPushSubscription())
|
||||
return subscription ? 'on' : 'off'
|
||||
}
|
||||
|
||||
/** Both halves of dropping a subscription, each best effort: the server's row and the browser's own. */
|
||||
async function forgetSubscription(subscription: PushSubscription): Promise<void> {
|
||||
await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(subscription.endpoint))
|
||||
await bestEffort('unsubscribing in the browser', () => subscription.unsubscribe())
|
||||
}
|
||||
|
||||
async function subscribeWithKey(
|
||||
registration: ServiceWorkerRegistration,
|
||||
key: Uint8Array<ArrayBuffer>,
|
||||
): Promise<PushSubscription> {
|
||||
const options: PushSubscriptionOptionsInit = { userVisibleOnly: true, applicationServerKey: key }
|
||||
try {
|
||||
return await registration.pushManager.subscribe(options)
|
||||
} catch (err) {
|
||||
// A subscription made with an earlier server key blocks a new one. Drop it
|
||||
// and try once more; any other failure is final.
|
||||
const stale = await registration.pushManager.getSubscription()
|
||||
if (!stale || keyMatches(stale.options?.applicationServerKey, key)) throw err
|
||||
await forgetSubscription(stale)
|
||||
return registration.pushManager.subscribe(options)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches push on for this device: the permission, then the browser's
|
||||
* subscription, then the server.
|
||||
*
|
||||
* Call it straight from the click handler, with the key and the registration
|
||||
* fetched beforehand. WebKit honours the permission prompt and subscribe() only
|
||||
* inside the user's gesture, and an awaited network call in front of them would
|
||||
* spend it. The permission request is therefore the first thing that runs.
|
||||
*/
|
||||
export async function enableWebPush(publicKey: string, registration?: ServiceWorkerRegistration | null): Promise<void> {
|
||||
const permission =
|
||||
Notification.permission === 'granted' ? 'granted' : await Notification.requestPermission()
|
||||
if (permission === 'denied') throw new WebPushError('denied')
|
||||
if (permission !== 'granted') throw new WebPushError('dismissed')
|
||||
|
||||
let subscription: PushSubscription
|
||||
try {
|
||||
const active = registration?.pushManager ? registration : await waitForPushRegistration()
|
||||
if (!active?.pushManager) throw new WebPushError('failed', 'no service worker')
|
||||
subscription = await subscribeWithKey(active, base64UrlToUint8Array(publicKey))
|
||||
} catch (err) {
|
||||
throw err instanceof WebPushError ? err : new WebPushError('failed', err)
|
||||
}
|
||||
|
||||
try {
|
||||
await pushApi.subscribe(toSubscriptionInput(subscription))
|
||||
} catch (err) {
|
||||
// The server never took this subscription, so it must not outlive the
|
||||
// failure: the card reads the browser's record, and would claim push works
|
||||
// on a device the server will never send to.
|
||||
await bestEffort('rolling back the browser subscription', () => subscription.unsubscribe())
|
||||
throw err instanceof WebPushError ? err : new WebPushError('failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches push off for this device. The server's row goes first, while this
|
||||
* session can still name the endpoint. If that request fails the browser still
|
||||
* unsubscribes: that alone stops delivery here, and the server drops a row the
|
||||
* push service answers 404 or 410 for on its next send.
|
||||
*/
|
||||
export async function disableWebPush(): Promise<void> {
|
||||
const subscription = await currentPushSubscription()
|
||||
if (!subscription) return
|
||||
await bestEffort('forgetting the device on the server', () => pushApi.unsubscribe(subscription.endpoint))
|
||||
await subscription.unsubscribe()
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the server about this device's subscription again after sign-in. The
|
||||
* server upserts by endpoint, so repeating it is harmless, and it heals a row
|
||||
* that was lost or still belongs to the account that used this browser before.
|
||||
*
|
||||
* When the server's key changed since the device subscribed, every push to the
|
||||
* old subscription fails its signature check, so it is replaced. Permission is
|
||||
* already granted then, which lets the browser subscribe again without a
|
||||
* gesture; where it refuses, the device simply reads as off and the card offers
|
||||
* to switch it on. Never rejects.
|
||||
*/
|
||||
export async function resyncPushSubscription(): Promise<void> {
|
||||
if (!getWebPushSupport().supported || getPushPermission() !== 'granted' || isEffectivelyOffline()) return
|
||||
await bestEffort('re-registering this device', async () => {
|
||||
const registration = await existingRegistration()
|
||||
const subscription = await registration?.pushManager?.getSubscription()
|
||||
if (!registration || !subscription) return
|
||||
const { publicKey } = await pushApi.getPublicKey()
|
||||
const key = base64UrlToUint8Array(publicKey)
|
||||
let current = subscription
|
||||
if (!keyMatches(subscription.options?.applicationServerKey, key)) {
|
||||
await forgetSubscription(subscription)
|
||||
current = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key })
|
||||
}
|
||||
await pushApi.subscribe(toSubscriptionInput(current))
|
||||
})
|
||||
}
|
||||
|
||||
/** Where the logout step tells the server to forget this device. */
|
||||
const PUSH_SUBSCRIPTIONS_URL = '/api/notifications/push/subscriptions'
|
||||
|
||||
/**
|
||||
* The server half of the logout teardown, as a plain fetch rather than through
|
||||
* apiClient: when the session has already run out the answer is a 401, and
|
||||
* apiClient meets that with its redirect to the login page, in the middle of
|
||||
* the logout. It carries its own timeout, so the request itself is cut off
|
||||
* rather than left running behind a logout that has moved on.
|
||||
*/
|
||||
async function forgetOnServerAtLogout(endpoint: string, timeoutMs: number): Promise<void> {
|
||||
const body: PushUnsubscribeRequest = { endpoint }
|
||||
const abort = new AbortController()
|
||||
const timer = setTimeout(() => abort.abort(), timeoutMs)
|
||||
try {
|
||||
const response = await fetch(PUSH_SUBSCRIPTIONS_URL, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
signal: abort.signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The logout step: forget this device on the server and in the browser, so the
|
||||
* next account on a shared device does not receive this one's notifications.
|
||||
* It has to run while the session cookie still exists, and it waits at most
|
||||
* `timeoutMs`. Never rejects, and never redirects: a server that already
|
||||
* dropped the session, never answers or cannot be reached only costs the
|
||||
* server half, the browser still unsubscribes.
|
||||
*
|
||||
* The two halves run side by side rather than one after the other. The server
|
||||
* half may use up the whole timeout, and the browser half is the one that
|
||||
* stops delivery here, so it must not queue behind it. The server needs
|
||||
* nothing the browser still has to hold: the endpoint is already in hand, and
|
||||
* a row left behind goes on the next send, when the push service answers 404
|
||||
* or 410.
|
||||
*/
|
||||
export async function forgetPushDeviceOnLogout(timeoutMs = LOGOUT_PUSH_TIMEOUT_MS): Promise<void> {
|
||||
if (!hasPushApis()) return
|
||||
const teardown = bestEffort('forgetting this device at logout', async () => {
|
||||
const subscription = await currentPushSubscription()
|
||||
if (!subscription) return
|
||||
await Promise.all([
|
||||
bestEffort('forgetting the device on the server', () => forgetOnServerAtLogout(subscription.endpoint, timeoutMs)),
|
||||
bestEffort('unsubscribing in the browser', () => subscription.unsubscribe()),
|
||||
])
|
||||
})
|
||||
await withTimeout(teardown, timeoutMs, undefined)
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { clearAllPluginSessions } from './pluginStore'
|
||||
import { forgetStartDestination } from '../utils/startDestination'
|
||||
import { forgetServerLanguage } from './settingsStore'
|
||||
import { markSignedOut, clearSignedOut } from '../utils/signedOut'
|
||||
import { forgetPushDeviceOnLogout, resyncPushSubscription } from '../push/webPush'
|
||||
|
||||
interface AuthResponse {
|
||||
user: User
|
||||
@@ -119,6 +120,9 @@ async function onAuthSuccess(userId: number): Promise<void> {
|
||||
// an SPA session, so a second login in the same tab would leave the mutation
|
||||
// queue without a flush trigger. Re-registering is a no-op while they are up.
|
||||
registerSyncTriggers()
|
||||
// Tell the server again which push subscription this device holds, in the
|
||||
// background: sign-in must not wait on it, and it never rejects.
|
||||
void resyncPushSubscription()
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
@@ -264,6 +268,11 @@ export const useAuthStore = create<AuthState>()(
|
||||
// and the next account would come up believing it is offline over a working
|
||||
// connection, with nothing cached to answer from.
|
||||
setForcedOffline(false)
|
||||
// Forget this device's push subscription, on the server and in the browser,
|
||||
// or the next account on a shared device keeps receiving this one's
|
||||
// notifications. It has to happen here: the DELETE needs the session cookie
|
||||
// that step 4 clears. Best effort and bounded, so logout never hangs on it.
|
||||
await forgetPushDeviceOnLogout()
|
||||
// 4. Tell server to clear the httpOnly cookie (best-effort).
|
||||
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {})
|
||||
// 5. Clear service worker caches containing sensitive data.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getCachedBlob } from '../db/offlineDb'
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import { isIosStandalone } from './iosDevice'
|
||||
|
||||
// MIME types safe to open inline (will not execute script in any browser).
|
||||
// Everything else (text/html, image/svg+xml, text/javascript, …) is forced to
|
||||
@@ -35,13 +36,6 @@ function triggerAnchorDownload(blobUrl: string, filename?: string): void {
|
||||
setTimeout(() => { URL.revokeObjectURL(blobUrl); a.remove() }, 100)
|
||||
}
|
||||
|
||||
// navigator.standalone is true only on iOS when running as an
|
||||
// add-to-home-screen PWA. In that context, target="_blank" hands off to
|
||||
// Safari, which cannot access blob URLs sandboxed to the WebView.
|
||||
function isIosStandalone(): boolean {
|
||||
return (navigator as any).standalone === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a protected file to a Blob, preferring the live server but falling
|
||||
* back to the offline cache (pre-downloaded by the trip sync manager). This is
|
||||
@@ -124,7 +118,8 @@ export async function openFile(url: string, filename?: string): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// iOS PWA: target="_blank" would open Safari, which can't access the blob
|
||||
// iOS PWA: target="_blank" hands off to Safari, which cannot reach a blob URL
|
||||
// sandboxed to the installed app's WebView.
|
||||
if (isIosStandalone()) {
|
||||
triggerAnchorDownload(blobUrl, filename)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* FE-IOS-001 to FE-IOS-004: the two iPhone and iPad facts shared by file
|
||||
* opening and Web Push.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { isIosDevice, isIosStandalone } from './iosDevice'
|
||||
|
||||
function define(name: 'userAgent' | 'maxTouchPoints' | 'standalone', value: unknown) {
|
||||
Object.defineProperty(navigator, name, { configurable: true, get: () => value })
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const name of ['userAgent', 'maxTouchPoints', 'standalone']) {
|
||||
delete (navigator as unknown as Record<string, unknown>)[name]
|
||||
}
|
||||
})
|
||||
|
||||
describe('isIosStandalone', () => {
|
||||
it("FE-IOS-001: is true only for Apple's own home-screen flag", () => {
|
||||
expect(isIosStandalone()).toBe(false)
|
||||
define('standalone', false)
|
||||
expect(isIosStandalone()).toBe(false)
|
||||
define('standalone', true)
|
||||
expect(isIosStandalone()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isIosDevice', () => {
|
||||
it('FE-IOS-002: recognises iPhone, iPod and iPad by their user agent', () => {
|
||||
for (const device of ['iPhone', 'iPod touch', 'iPad']) {
|
||||
define('userAgent', `Mozilla/5.0 (${device}; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15`)
|
||||
expect(isIosDevice()).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-IOS-003: an iPad asking for the desktop site is a Mac with a touch screen', () => {
|
||||
define('userAgent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15')
|
||||
define('maxTouchPoints', 5)
|
||||
expect(isIosDevice()).toBe(true)
|
||||
define('maxTouchPoints', 0)
|
||||
expect(isIosDevice()).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-IOS-004: Android and Windows are not iOS', () => {
|
||||
define('maxTouchPoints', 5)
|
||||
define('userAgent', 'Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 Chrome/140.0 Mobile Safari/537.36')
|
||||
expect(isIosDevice()).toBe(false)
|
||||
define('userAgent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/140.0 Safari/537.36')
|
||||
expect(isIosDevice()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* iPhone and iPad facts that more than one feature has to know about: file
|
||||
* opening needs to know whether a new tab would leave the installed app, and
|
||||
* Web Push needs to know whether it can work here at all.
|
||||
*/
|
||||
|
||||
type NavigatorWithStandalone = Navigator & { standalone?: boolean }
|
||||
|
||||
/**
|
||||
* True only on iOS and iPadOS while TREK runs as an app added to the Home
|
||||
* Screen. `navigator.standalone` is Apple's own flag and exists nowhere else,
|
||||
* so every other platform answers false.
|
||||
*/
|
||||
export function isIosStandalone(): boolean {
|
||||
return typeof navigator !== 'undefined' && (navigator as NavigatorWithStandalone).standalone === true
|
||||
}
|
||||
|
||||
/**
|
||||
* True on iPhone, iPod touch and iPad. iPadOS 13 and later asks for the desktop
|
||||
* site by default and then introduces itself as a Mac, so a Mac with a touch
|
||||
* screen counts too: no real Mac has one.
|
||||
*/
|
||||
export function isIosDevice(): boolean {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
const ua = navigator.userAgent || ''
|
||||
if (/iPad|iPhone|iPod/.test(ua)) return true
|
||||
return /Macintosh/.test(ua) && (navigator.maxTouchPoints ?? 0) > 1
|
||||
}
|
||||
Reference in New Issue
Block a user