Add push notification functionality with tests and digest scheduler
All checks were successful
Chore App Build, Test, and Push Docker Images / build-and-push (push) Successful in 2m14s

- Implemented push subscription API with tests for subscribing and unsubscribing users.
- Created web push notification tests triggered by child actions.
- Added digest scheduler to send email digests to users at 9 PM local time.
- Developed utility functions for creating and validating digest action tokens.
- Integrated web push sender to handle sending notifications to users.
- Added service worker for handling push notifications in the frontend.
- Created a push opt-in component for user notification preferences.
- Implemented tests for the push opt-in component to ensure correct behavior.
- Updated frontend services to manage push subscriptions and permissions.
This commit is contained in:
2026-04-15 21:56:10 -04:00
parent 0d50a324a3
commit ad2bdf4c4f
47 changed files with 3177 additions and 197 deletions

View File

@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<link rel="manifest" href="/manifest.json" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
@@ -12,5 +13,14 @@
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').catch(function (err) {
console.warn('Service Worker registration failed:', err)
})
})
}
</script>
</body>
</html>

View File

@@ -0,0 +1,16 @@
{
"name": "Reward App",
"short_name": "Rewards",
"start_url": "/",
"display": "standalone",
"theme_color": "#4a90e2",
"background_color": "#ffffff",
"description": "Track chores and rewards for your family",
"icons": [
{
"src": "/favicon.ico",
"sizes": "48x48",
"type": "image/x-icon"
}
]
}

View File

@@ -0,0 +1,68 @@
/* Service Worker for Reward App push notifications */
self.addEventListener('push', function (event) {
if (!event.data) return
let payload
try {
payload = event.data.json()
} catch (e) {
payload = { title: 'Reward App', body: event.data.text() }
}
const title = payload.title || 'Reward App'
const options = {
body: payload.body || '',
data: payload,
actions: [
{ action: 'approve', title: 'Approve' },
{ action: 'deny', title: 'Deny' },
],
}
event.waitUntil(self.registration.showNotification(title, options))
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
const payload = event.notification.data || {}
const approveToken = payload.approve_token
const denyToken = payload.deny_token
const childId = payload.child_id
const entityId = payload.entity_id
const entityType = payload.entity_type
if (event.action === 'approve' && approveToken) {
event.waitUntil(fetch('/api/digest-action/' + approveToken))
return
}
if (event.action === 'deny' && denyToken) {
event.waitUntil(fetch('/api/digest-action/' + denyToken))
return
}
// Body tap — open or focus the app then navigate to the deep link
const deepLinkUrl =
childId && entityId && entityType
? '/parent/' + childId + '?scrollTo=' + entityId + '&entityType=' + entityType
: '/parent'
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (clientList) {
const sameOriginClients = clientList.filter(function (c) {
return new URL(c.url).origin === self.location.origin
})
if (sameOriginClients.length > 0) {
const client = sameOriginClients[0]
return client.focus().then(function () {
return client.navigate(deepLinkUrl)
})
}
return clients.openWindow(deepLinkUrl)
}),
)
})

View File

@@ -549,3 +549,119 @@ describe('UserProfile - Profile Update', () => {
expect(wrapper.vm.loading).toBe(false)
})
})
describe('UserProfile - Email Digest Toggle', () => {
let wrapper: VueWrapper<any>
function mountWithDigest(emailDigestEnabled: boolean) {
;(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => ({
image_id: null,
first_name: 'Test',
last_name: 'User',
email: 'test@example.com',
email_digest_enabled: emailDigestEnabled,
}),
})
return mount(UserProfile, {
global: {
plugins: [mockRouter],
stubs: {
EntityEditForm: {
template: '<div><slot /></div>',
},
ModalDialog: {
template: '<div class="mock-modal" v-if="show"><slot /></div>',
props: ['show'],
},
},
},
})
}
beforeEach(() => {
vi.clearAllMocks()
;(global.fetch as any).mockClear()
// Default response for any extra fetch calls (e.g. PUT)
;(global.fetch as any).mockResolvedValue({
ok: true,
json: async () => ({}),
})
})
it('renders the email digest toggle button', async () => {
wrapper = mountWithDigest(true)
await flushPromises()
await nextTick()
expect(wrapper.find('.toggle-btn').exists()).toBe(true)
})
it('initializes toggle as enabled when email_digest_enabled is true', async () => {
wrapper = mountWithDigest(true)
await flushPromises()
await nextTick()
expect(wrapper.vm.emailDigestEnabled).toBe(true)
expect(wrapper.find('.toggle-btn').attributes('aria-pressed')).toBe('true')
})
it('initializes toggle as disabled when email_digest_enabled is false', async () => {
wrapper = mountWithDigest(false)
await flushPromises()
await nextTick()
expect(wrapper.vm.emailDigestEnabled).toBe(false)
expect(wrapper.find('.toggle-btn').attributes('aria-pressed')).toBe('false')
})
it('calls PUT /api/user/profile with email_digest_enabled: false when toggled off', async () => {
wrapper = mountWithDigest(true)
await flushPromises()
await nextTick()
;(global.fetch as any).mockResolvedValueOnce({ ok: true, json: async () => ({}) })
await wrapper.vm.toggleDigest()
await flushPromises()
expect(global.fetch).toHaveBeenCalledWith(
'/api/user/profile',
expect.objectContaining({
method: 'PUT',
body: JSON.stringify({ email_digest_enabled: false }),
}),
)
})
it('calls PUT /api/user/profile with email_digest_enabled: true when toggled on', async () => {
wrapper = mountWithDigest(false)
await flushPromises()
await nextTick()
;(global.fetch as any).mockResolvedValueOnce({ ok: true, json: async () => ({}) })
await wrapper.vm.toggleDigest()
await flushPromises()
expect(global.fetch).toHaveBeenCalledWith(
'/api/user/profile',
expect.objectContaining({
method: 'PUT',
body: JSON.stringify({ email_digest_enabled: true }),
}),
)
})
it('flips emailDigestEnabled state after toggle', async () => {
wrapper = mountWithDigest(true)
await flushPromises()
await nextTick()
;(global.fetch as any).mockResolvedValueOnce({ ok: true, json: async () => ({}) })
expect(wrapper.vm.emailDigestEnabled).toBe(true)
await wrapper.vm.toggleDigest()
await flushPromises()
expect(wrapper.vm.emailDigestEnabled).toBe(false)
})
})

View File

@@ -63,6 +63,8 @@ export interface User {
deletion_in_progress: boolean
deletion_attempted_at: string | null
role: string
timezone: string | null
email_digest_enabled: boolean
}
export interface Child {

View File

@@ -14,6 +14,9 @@ vi.mock('../../stores/auth', () => ({
isParentPersistent: { value: false },
logoutParent: vi.fn(),
logoutUser: vi.fn(),
consumePendingReturnUrl: vi.fn(() => null),
hasPendingReturnUrl: vi.fn(() => false),
clearPendingReturnUrl: vi.fn(),
}))
vi.mock('@/common/imageCache', () => ({

View File

@@ -612,6 +612,22 @@ async function fetchChildData(id: string | number) {
}
}
function applyHighlightPulse(itemId: string) {
// Delay slightly so the scroll animation has time to settle
setTimeout(() => {
const el = document.querySelector(`[data-item-id="${itemId}"]`)
if (!el) return
el.classList.add('highlight-pulse')
el.addEventListener(
'animationend',
() => {
el.classList.remove('highlight-pulse')
},
{ once: true },
)
}, 200)
}
onMounted(async () => {
try {
eventBus.on('child_task_triggered', handleTaskTriggered)
@@ -648,8 +664,10 @@ onMounted(async () => {
setTimeout(() => {
if (entityType === 'chore') {
childChoreListRef.value?.scrollToItem(scrollToId)
applyHighlightPulse(scrollToId)
} else if (entityType === 'reward') {
childRewardListRef.value?.scrollToItem(scrollToId)
applyHighlightPulse(scrollToId)
}
}, 500)
}
@@ -1404,4 +1422,23 @@ function goToAssignRewards() {
.input-group input.invalid {
border-color: var(--error-color, #e53e3e);
}
@keyframes highlight-pulse {
0% {
box-shadow: 0 0 0 0 var(--accent, #4a90e2);
outline: 2px solid var(--accent, #4a90e2);
}
50% {
box-shadow: 0 0 16px 4px var(--accent, #4a90e2);
outline: 2px solid var(--accent, #4a90e2);
}
100% {
box-shadow: none;
outline: none;
}
}
:global(.highlight-pulse) {
animation: highlight-pulse 1.8s ease-out forwards;
}
</style>

View File

@@ -538,4 +538,56 @@ describe('ParentView', () => {
expect(wrapper.vm.selectedChoreId).toBe(null)
})
})
describe('Highlight pulse animation', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('adds highlight-pulse class to element with matching data-item-id', async () => {
const el = document.createElement('div')
el.setAttribute('data-item-id', 'task-1')
document.body.appendChild(el)
wrapper = mount(ParentView, mountOptions)
wrapper.vm.applyHighlightPulse('task-1')
vi.advanceTimersByTime(200)
expect(el.classList.contains('highlight-pulse')).toBe(true)
document.body.removeChild(el)
})
it('removes highlight-pulse class when animationend fires', async () => {
const el = document.createElement('div')
el.setAttribute('data-item-id', 'task-1')
document.body.appendChild(el)
wrapper = mount(ParentView, mountOptions)
wrapper.vm.applyHighlightPulse('task-1')
vi.advanceTimersByTime(200)
expect(el.classList.contains('highlight-pulse')).toBe(true)
el.dispatchEvent(new Event('animationend'))
expect(el.classList.contains('highlight-pulse')).toBe(false)
document.body.removeChild(el)
})
it('does nothing when no element with matching data-item-id exists', () => {
wrapper = mount(ParentView, mountOptions)
// Should not throw
expect(() => {
wrapper.vm.applyHighlightPulse('nonexistent-id')
vi.advanceTimersByTime(200)
}).not.toThrow()
})
})
})

View File

@@ -0,0 +1,91 @@
<template>
<div v-if="showBanner" class="push-opt-in-banner" role="status" aria-live="polite">
<template v-if="permissionState === 'default'">
<span class="push-opt-in-text"
>Enable notifications to stay updated on chores and rewards.</span
>
<button class="btn btn-primary push-opt-in-btn" @click="onEnable">Enable</button>
<button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss"></button>
</template>
<template v-else-if="permissionState === 'denied'">
<span class="push-opt-in-text"
>Notifications are blocked. Enable them in your browser settings to receive alerts.</span
>
<button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss"></button>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { subscribeToPush, getPushPermissionState } from '@/services/pushSubscription'
const permissionState = ref<NotificationPermission | 'unsupported'>('default')
const dismissed = ref(false)
const showBanner = ref(false)
onMounted(() => {
if (!('Notification' in window)) {
return
}
permissionState.value = Notification.permission
if (permissionState.value === 'granted') {
// Already granted — ensure subscription is registered silently
subscribeToPush()
return
}
showBanner.value = true
})
async function onEnable() {
const success = await subscribeToPush()
if (success) {
permissionState.value = 'granted'
showBanner.value = false
} else {
permissionState.value = Notification.permission as NotificationPermission
}
}
function dismiss() {
dismissed.value = true
showBanner.value = false
}
</script>
<style scoped>
.push-opt-in-banner {
display: flex;
align-items: center;
gap: 0.75rem;
background: var(--list-item-bg, #f0f4ff);
border: 1px solid var(--btn-primary, #4a90e2);
border-radius: 8px;
padding: 0.6rem 1rem;
margin: 0.5rem 0;
font-size: 0.88rem;
flex-wrap: wrap;
}
.push-opt-in-text {
flex: 1;
min-width: 0;
}
.push-opt-in-btn {
font-size: 0.85rem;
padding: 0.35rem 0.9rem;
white-space: nowrap;
}
.push-opt-in-dismiss {
background: none;
border: none;
cursor: pointer;
color: var(--text-muted, #888);
font-size: 1rem;
padding: 0 0.25rem;
line-height: 1;
}
</style>

View File

@@ -0,0 +1,133 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import PushOptIn from '../PushOptIn.vue'
const mockSubscribeToPush = vi.fn()
const mockGetPushPermissionState = vi.fn()
vi.mock('@/services/pushSubscription', () => ({
subscribeToPush: () => mockSubscribeToPush(),
getPushPermissionState: () => mockGetPushPermissionState(),
}))
function setupNotificationMock(permission: NotificationPermission) {
Object.defineProperty(window, 'Notification', {
writable: true,
value: { permission },
})
}
describe('PushOptIn', () => {
afterEach(() => {
vi.clearAllMocks()
})
describe('permission already granted on mount', () => {
beforeEach(() => {
setupNotificationMock('granted')
mockSubscribeToPush.mockResolvedValue(true)
})
it('silently calls subscribeToPush without showing the banner', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).toHaveBeenCalledOnce()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
})
describe('permission default (not yet asked)', () => {
beforeEach(() => {
setupNotificationMock('default')
})
it('shows the opt-in banner with Enable button', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
expect(wrapper.find('.push-opt-in-btn').text()).toBe('Enable')
})
it('does NOT call subscribeToPush on mount', async () => {
mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
})
it('calls subscribeToPush when Enable button is clicked', async () => {
mockSubscribeToPush.mockResolvedValue(true)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
expect(mockSubscribeToPush).toHaveBeenCalledOnce()
})
it('hides banner after Enable is clicked and subscription succeeds', async () => {
mockSubscribeToPush.mockResolvedValue(true)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
it('does NOT post subscription to backend when subscribeToPush returns false', async () => {
mockSubscribeToPush.mockResolvedValue(false)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
// Banner should still be visible (permission was denied)
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
})
it('hides banner on dismiss without calling subscribeToPush', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-dismiss').trigger('click')
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
})
describe('permission denied', () => {
beforeEach(() => {
setupNotificationMock('denied')
})
it('shows the blocked message banner', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
expect(wrapper.find('.push-opt-in-banner').text()).toContain('blocked')
})
it('does NOT show the Enable button when permission is denied', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-btn').exists()).toBe(false)
})
it('does NOT call subscribeToPush on mount when already denied', async () => {
mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
})
})
})

View File

@@ -32,6 +32,29 @@
</div>
</template>
</EntityEditForm>
<div class="digest-section">
<div class="digest-row">
<div class="digest-label">
<span class="digest-title">Daily Email Digest</span>
<span class="digest-desc"
>Receive a 9pm summary of pending chore and reward requests with one-click approve/deny
links.</span
>
</div>
<button
type="button"
:class="['toggle-btn', { active: emailDigestEnabled }]"
:aria-pressed="emailDigestEnabled"
:disabled="savingDigest"
@click="toggleDigest"
>
<span class="toggle-knob" />
</button>
</div>
<div v-if="digestError" class="error-message digest-error">{{ digestError }}</div>
</div>
<div v-if="errorMsg" class="error-message" aria-live="polite">{{ errorMsg }}</div>
<ModalDialog
v-if="showModal"
@@ -124,6 +147,10 @@ const showDeleteSuccess = ref(false)
const showDeleteError = ref(false)
const deleteErrorMessage = ref('')
const emailDigestEnabled = ref(true)
const savingDigest = ref(false)
const digestError = ref('')
const initialData = ref<{
image_id: string | null
first_name: string
@@ -162,6 +189,7 @@ onMounted(async () => {
last_name: data.last_name || '',
email: data.email || '',
}
emailDigestEnabled.value = data.email_digest_enabled !== false
} catch {
errorMsg.value = 'Could not load user profile.'
} finally {
@@ -283,6 +311,25 @@ async function resetPassword() {
}
}
async function toggleDigest() {
digestError.value = ''
const newValue = !emailDigestEnabled.value
savingDigest.value = true
try {
const res = await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email_digest_enabled: newValue }),
})
if (!res.ok) throw new Error('Failed to update preference')
emailDigestEnabled.value = newValue
} catch {
digestError.value = 'Failed to save notification preference.'
} finally {
savingDigest.value = false
}
}
function goToChangeParentPin() {
router.push({ name: 'ParentPinSetup' })
}
@@ -429,4 +476,80 @@ function closeDeleteError() {
outline: none;
border-color: var(--btn-primary, #4a90e2);
}
.digest-section {
margin-top: 1.5rem;
padding: 1rem 1.2rem;
border-radius: 10px;
background: var(--list-item-bg, #f9f9f9);
border: 1px solid var(--form-input-border, #e6e6e6);
}
.digest-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.digest-label {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.digest-title {
font-weight: 600;
font-size: 0.97rem;
color: var(--text, #1a1a1a);
}
.digest-desc {
font-size: 0.83rem;
color: var(--text-muted, #666);
line-height: 1.4;
}
.digest-error {
margin-top: 0.5rem;
}
.toggle-btn {
flex-shrink: 0;
width: 44px;
height: 24px;
border-radius: 12px;
border: none;
background: var(--form-input-border, #ccc);
cursor: pointer;
position: relative;
transition: background 0.2s;
padding: 0;
}
.toggle-btn.active {
background: var(--btn-primary, #4a90e2);
}
.toggle-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.toggle-knob {
display: block;
width: 18px;
height: 18px;
border-radius: 50%;
background: white;
position: absolute;
top: 3px;
left: 3px;
transition: left 0.2s;
pointer-events: none;
}
.toggle-btn.active .toggle-knob {
left: 23px;
}
</style>

View File

@@ -8,6 +8,9 @@ import {
isParentPersistent,
logoutParent,
logoutUser,
consumePendingReturnUrl,
hasPendingReturnUrl,
clearPendingReturnUrl,
} from '../../stores/auth'
import { getCachedImageUrl, getCachedImageBlob } from '@/common/imageCache'
import '@/assets/styles.css'
@@ -105,6 +108,7 @@ const close = () => {
show.value = false
error.value = ''
stayInParentMode.value = false
clearPendingReturnUrl()
}
const submit = async () => {
@@ -136,7 +140,8 @@ const submit = async () => {
// Authenticate parent and navigate
authenticateParent(stayInParentMode.value)
close()
router.push('/parent')
const returnUrl = consumePendingReturnUrl()
router.push(returnUrl || '/parent')
} catch (e) {
error.value = 'Network error'
}
@@ -253,6 +258,9 @@ onMounted(() => {
eventBus.on('profile_updated', fetchUserProfile)
document.addEventListener('mousedown', handleClickOutside)
fetchUserProfile()
if (!isParentAuthenticated.value && hasPendingReturnUrl()) {
open()
}
})
onUnmounted(() => {

View File

@@ -206,6 +206,7 @@ onBeforeUnmount(() => {
props.getItemClass?.(item),
{ 'item-ready': props.readyItemId === item.id },
]"
:data-item-id="item.id"
:ref="(el) => (itemRefs[item.id] = el)"
@click.stop="handleClicked(item)"
>

View File

@@ -32,6 +32,9 @@ vi.mock('../../../stores/auth', () => ({
isParentPersistent: isParentPersistentRef,
logoutParent: vi.fn(),
logoutUser: vi.fn(),
consumePendingReturnUrl: vi.fn(() => null),
hasPendingReturnUrl: vi.fn(() => false),
clearPendingReturnUrl: vi.fn(),
}))
global.fetch = vi.fn()

View File

@@ -2,6 +2,7 @@
import { useRouter, useRoute } from 'vue-router'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import LoginButton from '../components/shared/LoginButton.vue'
import PushOptIn from '../components/notification/PushOptIn.vue'
import { eventBus } from '@/common/eventBus'
import type {
Event,
@@ -165,6 +166,7 @@ onUnmounted(() => {
</header>
<main class="main-content">
<PushOptIn />
<router-view :key="$route.fullPath" />
</main>

View File

@@ -13,6 +13,7 @@ vi.mock('@/stores/auth', () => ({
isUserLoggedIn: isUserLoggedInMock,
isParentAuthenticated: isParentAuthenticatedMock,
enforceParentExpiry: vi.fn(),
setPendingReturnUrl: vi.fn(),
}))
// Import router AFTER mocks are in place

View File

@@ -29,6 +29,7 @@ import {
isParentAuthenticated,
isAuthReady,
enforceParentExpiry,
setPendingReturnUrl,
} from '../stores/auth'
import ParentPinSetup from '@/components/auth/ParentPinSetup.vue'
import LandingPage from '@/components/landing/LandingPage.vue'
@@ -303,6 +304,9 @@ router.beforeEach(async (to, from, next) => {
if (isParentAuthenticated.value) {
return next('/parent')
} else {
if (to.path.startsWith('/parent')) {
setPendingReturnUrl(to.fullPath)
}
return next('/child')
}
})

View File

@@ -0,0 +1,103 @@
/**
* Push subscription manager.
* Handles requesting notification permission, subscribing to push,
* and syncing the subscription with the backend.
*/
async function fetchVapidPublicKey(): Promise<string | null> {
try {
const res = await fetch('/api/push-vapid-key')
if (!res.ok) return null
const data = await res.json()
return data.public_key || null
} catch {
return null
}
}
function urlBase64ToUint8Array(base64String: string): Uint8Array {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
const rawData = window.atob(base64)
return Uint8Array.from([...rawData].map((c) => c.charCodeAt(0)))
}
/**
* Request notification permission and subscribe to push notifications.
* Posts the subscription to the backend, including the user's timezone.
* Returns true if subscription was successfully registered.
*/
export async function subscribeToPush(): Promise<boolean> {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
return false
}
try {
const permission = await Notification.requestPermission()
if (permission !== 'granted') {
return false
}
const vapidKey = await fetchVapidPublicKey()
if (!vapidKey) {
console.warn('[Push] VAPID public key not available; skipping subscription')
return false
}
const registration = await navigator.serviceWorker.ready
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidKey),
})
const subJson = subscription.toJSON()
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const res = await fetch('/api/push-subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
endpoint: subJson.endpoint,
keys: subJson.keys,
timezone,
}),
})
return res.ok
} catch (err) {
console.warn('[Push] Failed to subscribe:', err)
return false
}
}
/**
* Unsubscribe from push notifications and remove the subscription from the backend.
*/
export async function unsubscribeFromPush(): Promise<void> {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) return
try {
const registration = await navigator.serviceWorker.ready
const subscription = await registration.pushManager.getSubscription()
if (!subscription) return
const endpoint = subscription.endpoint
await subscription.unsubscribe()
await fetch('/api/push-subscription', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ endpoint }),
})
} catch (err) {
console.warn('[Push] Failed to unsubscribe:', err)
}
}
/**
* Check the current push permission state without prompting.
*/
export function getPushPermissionState(): NotificationPermission | 'unsupported' {
if (!('Notification' in window)) return 'unsupported'
return Notification.permission
}

View File

@@ -4,6 +4,7 @@ const hasLocalStorage =
typeof localStorage !== 'undefined' && typeof localStorage.getItem === 'function'
const AUTH_SYNC_EVENT_KEY = 'authSyncEvent'
const PARENT_AUTH_KEY = 'parentAuth'
const PARENT_RETURN_URL_KEY = 'parentReturnUrl'
const PARENT_AUTH_EXPIRY_NON_PERSISTENT = 60_000 // 1 minute
const PARENT_AUTH_EXPIRY_PERSISTENT = 172_800_000 // 2 days
@@ -71,6 +72,33 @@ export function enforceParentExpiry() {
runExpiryCheck()
}
export function setPendingReturnUrl(url: string) {
if (!url.startsWith('/parent')) return
if (hasLocalStorage) {
localStorage.setItem(PARENT_RETURN_URL_KEY, url)
}
}
export function consumePendingReturnUrl(): string | null {
if (!hasLocalStorage) return null
const url = localStorage.getItem(PARENT_RETURN_URL_KEY)
if (url) {
localStorage.removeItem(PARENT_RETURN_URL_KEY)
}
return url
}
export function hasPendingReturnUrl(): boolean {
if (!hasLocalStorage) return false
return localStorage.getItem(PARENT_RETURN_URL_KEY) !== null
}
export function clearPendingReturnUrl() {
if (hasLocalStorage) {
localStorage.removeItem(PARENT_RETURN_URL_KEY)
}
}
export function authenticateParent(persistent: boolean) {
const duration = persistent ? PARENT_AUTH_EXPIRY_PERSISTENT : PARENT_AUTH_EXPIRY_NON_PERSISTENT
parentAuthExpiresAt.value = Date.now() + duration