The tree carried uncommitted work from several areas (web push, mobile screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed as one commit so the release pipeline can start from a clean tree; the desktop transcript-correction behaviour shipped in the previous commit and is unchanged here.
504 lines
15 KiB
TypeScript
504 lines
15 KiB
TypeScript
import { describe, expect, test } from 'vitest'
|
|
import type { getSupabaseBrowserClient } from '../src/lib/supabase-browser'
|
|
import {
|
|
describeWebBrowserDevice,
|
|
ensureCurrentWebDevice,
|
|
getOrCreateWebInstallationId,
|
|
getStoredWebInstallationId,
|
|
} from '../src/lib/web-device'
|
|
import {
|
|
requestWebPushPermission,
|
|
subscribeWebPush,
|
|
unsubscribeWebPush,
|
|
} from '../src/lib/web-push'
|
|
import {
|
|
disableCurrentWebPush,
|
|
getCurrentWebPushConnectionStatus,
|
|
reconcileFailedWebPushEnable,
|
|
signOutWithoutWaitingForWebPushCleanup,
|
|
} from '../src/lib/web-push-session'
|
|
|
|
type WebClient = ReturnType<typeof getSupabaseBrowserClient>
|
|
|
|
const USER_ID = '00000000-0000-4000-8000-000000000001'
|
|
const DEVICE_ID = '00000000-0000-4000-8000-000000000002'
|
|
const VAPID_KEY = 'AQIDBAUGBwgJCgsMDQ4PEA'
|
|
|
|
function installPushBrowser(
|
|
permission: NotificationPermission,
|
|
requestPermission: () => Promise<NotificationPermission>,
|
|
): () => void {
|
|
const keys = ['window', 'navigator', 'Notification'] as const
|
|
const originals = new Map(keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]))
|
|
|
|
Object.defineProperty(globalThis, 'window', {
|
|
configurable: true,
|
|
value: { PushManager: class TestPushManager {} },
|
|
})
|
|
Object.defineProperty(globalThis, 'navigator', {
|
|
configurable: true,
|
|
value: { serviceWorker: {} },
|
|
})
|
|
Object.defineProperty(globalThis, 'Notification', {
|
|
configurable: true,
|
|
value: { permission, requestPermission },
|
|
})
|
|
|
|
return () => {
|
|
for (const key of keys) {
|
|
const descriptor = originals.get(key)
|
|
if (descriptor) Object.defineProperty(globalThis, key, descriptor)
|
|
else Reflect.deleteProperty(globalThis, key)
|
|
}
|
|
}
|
|
}
|
|
|
|
function memoryStorage(initial?: Record<string, string>): Storage {
|
|
const values = new Map(Object.entries(initial ?? {}))
|
|
return {
|
|
get length() {
|
|
return values.size
|
|
},
|
|
clear: () => values.clear(),
|
|
getItem: (key) => values.get(key) ?? null,
|
|
key: (index) => [...values.keys()][index] ?? null,
|
|
removeItem: (key) => {
|
|
values.delete(key)
|
|
},
|
|
setItem: (key, value) => {
|
|
values.set(key, value)
|
|
},
|
|
}
|
|
}
|
|
|
|
function pushSubscription(
|
|
onUnsubscribe?: () => void,
|
|
unsubscribeError?: Error,
|
|
): PushSubscription {
|
|
return {
|
|
endpoint: 'https://push.example/subscription/1',
|
|
expirationTime: null,
|
|
options: {
|
|
applicationServerKey: null,
|
|
userVisibleOnly: true,
|
|
},
|
|
getKey: () => null,
|
|
toJSON: () => ({
|
|
endpoint: 'https://push.example/subscription/1',
|
|
keys: { auth: 'auth-key', p256dh: 'p256dh-key' },
|
|
}),
|
|
unsubscribe: async () => {
|
|
onUnsubscribe?.()
|
|
if (unsubscribeError) throw unsubscribeError
|
|
return true
|
|
},
|
|
}
|
|
}
|
|
|
|
function activeDeviceClient(
|
|
rpc: (name: string, args: unknown) => Promise<{ data: unknown; error: { message: string } | null }>,
|
|
): WebClient {
|
|
const chain = {
|
|
select: () => chain,
|
|
eq: () => chain,
|
|
maybeSingle: async () => ({
|
|
data: { id: DEVICE_ID, revoked_at: null },
|
|
error: null,
|
|
}),
|
|
}
|
|
return {
|
|
from: () => chain,
|
|
rpc,
|
|
} as unknown as WebClient
|
|
}
|
|
|
|
function registration(
|
|
subscription: PushSubscription | null,
|
|
onSubscribe?: () => void,
|
|
): ServiceWorkerRegistration {
|
|
return {
|
|
pushManager: {
|
|
getSubscription: async () => subscription,
|
|
permissionState: async () => 'granted',
|
|
subscribe: async () => {
|
|
onSubscribe?.()
|
|
if (!subscription) throw new Error('test registration requires a subscription')
|
|
return subscription
|
|
},
|
|
},
|
|
} as ServiceWorkerRegistration
|
|
}
|
|
|
|
describe('web push client contract', () => {
|
|
test('requests permission only after confirming the public VAPID key exists', async () => {
|
|
let permissionRequests = 0
|
|
const restore = installPushBrowser('default', async () => {
|
|
permissionRequests += 1
|
|
return 'granted'
|
|
})
|
|
try {
|
|
await expect(requestWebPushPermission('')).rejects.toMatchObject({
|
|
code: 'vapid-key-missing',
|
|
})
|
|
expect(permissionRequests).toBe(0)
|
|
|
|
await expect(requestWebPushPermission(VAPID_KEY)).resolves.toBeUndefined()
|
|
expect(permissionRequests).toBe(1)
|
|
} finally {
|
|
restore()
|
|
}
|
|
})
|
|
|
|
test('keeps one valid browser installation ID and replaces invalid stored data', () => {
|
|
const storage = memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': 'invalid',
|
|
})
|
|
expect(getStoredWebInstallationId(storage)).toBeNull()
|
|
|
|
const installationId = getOrCreateWebInstallationId(storage, () => DEVICE_ID)
|
|
expect(installationId).toBe(DEVICE_ID)
|
|
expect(getOrCreateWebInstallationId(storage, () => USER_ID)).toBe(DEVICE_ID)
|
|
})
|
|
|
|
test('derives bounded browser device metadata without persisting the full user agent', () => {
|
|
expect(describeWebBrowserDevice(
|
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0 Safari/537.36',
|
|
'Win32',
|
|
)).toEqual({ deviceName: 'Chrome · Windows', osVersion: 'Win32' })
|
|
})
|
|
|
|
test('creates a web device with the stable installation ID before push registration', async () => {
|
|
const inserts: unknown[] = []
|
|
const readChain = {
|
|
select: () => readChain,
|
|
eq: () => readChain,
|
|
maybeSingle: async () => ({ data: null, error: null }),
|
|
}
|
|
const client = {
|
|
from: () => ({
|
|
...readChain,
|
|
insert: (value: unknown) => {
|
|
inserts.push(value)
|
|
return {
|
|
select: () => ({
|
|
single: async () => ({
|
|
data: { id: DEVICE_ID, revoked_at: null },
|
|
error: null,
|
|
}),
|
|
}),
|
|
}
|
|
},
|
|
}),
|
|
} as unknown as WebClient
|
|
|
|
await expect(ensureCurrentWebDevice(USER_ID, '1.16.1', {
|
|
client,
|
|
storage: memoryStorage(),
|
|
uuidFactory: () => DEVICE_ID,
|
|
now: () => new Date('2026-11-04T00:00:00.000Z'),
|
|
deviceName: 'Chrome · Windows',
|
|
osVersion: 'Win32',
|
|
})).resolves.toEqual({
|
|
id: DEVICE_ID,
|
|
installationId: DEVICE_ID,
|
|
revokedAt: null,
|
|
})
|
|
expect(inserts).toEqual([{
|
|
user_id: USER_ID,
|
|
installation_id: DEVICE_ID,
|
|
platform: 'web',
|
|
device_name: 'Chrome · Windows',
|
|
app_version: '1.16.1',
|
|
os_version: 'Win32',
|
|
last_seen_at: '2026-11-04T00:00:00.000Z',
|
|
}])
|
|
})
|
|
|
|
test('never resurrects a revoked browser device', async () => {
|
|
const chain = {
|
|
select: () => chain,
|
|
eq: () => chain,
|
|
maybeSingle: async () => ({
|
|
data: { id: DEVICE_ID, revoked_at: '2026-11-03T00:00:00.000Z' },
|
|
error: null,
|
|
}),
|
|
}
|
|
const client = {
|
|
from: () => chain,
|
|
} as unknown as WebClient
|
|
|
|
await expect(ensureCurrentWebDevice(USER_ID, '1.16.1', {
|
|
client,
|
|
storage: memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
}),
|
|
deviceName: 'Chrome · Windows',
|
|
})).rejects.toMatchObject({ code: 'device-revoked' })
|
|
})
|
|
|
|
test('subscribes only once and persists through the device-bound RPC', async () => {
|
|
const calls: Array<{ name: string; args: unknown }> = []
|
|
const subscription = pushSubscription()
|
|
const client = {
|
|
rpc: async (name: string, args: unknown) => {
|
|
calls.push({ name, args })
|
|
return {
|
|
data: {
|
|
device_id: DEVICE_ID,
|
|
provider: 'webpush',
|
|
registered_at: '2026-11-04T00:00:00.000Z',
|
|
},
|
|
error: null,
|
|
}
|
|
},
|
|
} as unknown as WebClient
|
|
|
|
const result = await subscribeWebPush({
|
|
userId: USER_ID,
|
|
deviceId: DEVICE_ID,
|
|
vapidPublicKey: VAPID_KEY,
|
|
client,
|
|
registration: registration(subscription),
|
|
})
|
|
|
|
expect(calls).toEqual([{
|
|
name: 'register_push_registration',
|
|
args: {
|
|
push_device_id: DEVICE_ID,
|
|
push_provider: 'webpush',
|
|
registration_id: JSON.stringify(subscription.toJSON()),
|
|
},
|
|
}])
|
|
expect(result).toMatchObject({
|
|
provider: 'webpush',
|
|
endpoint: subscription.endpoint,
|
|
registeredAt: '2026-11-04T00:00:00.000Z',
|
|
})
|
|
})
|
|
|
|
test('rolls back the browser subscription when persistence fails', async () => {
|
|
let unsubscribeCalls = 0
|
|
const subscription = pushSubscription(() => {
|
|
unsubscribeCalls += 1
|
|
})
|
|
const client = {
|
|
rpc: async () => ({ data: null, error: { message: 'database unavailable' } }),
|
|
} as unknown as WebClient
|
|
|
|
await expect(subscribeWebPush({
|
|
userId: USER_ID,
|
|
deviceId: DEVICE_ID,
|
|
vapidPublicKey: VAPID_KEY,
|
|
client,
|
|
registration: registration(subscription),
|
|
})).rejects.toMatchObject({ code: 'persistence-failed' })
|
|
expect(unsubscribeCalls).toBe(1)
|
|
})
|
|
|
|
test('removes the server registration and browser subscription together', async () => {
|
|
let unsubscribeCalls = 0
|
|
const client = {
|
|
rpc: async () => ({
|
|
data: { device_id: DEVICE_ID, removed: true },
|
|
error: null,
|
|
}),
|
|
} as unknown as WebClient
|
|
|
|
await expect(unsubscribeWebPush({
|
|
deviceId: DEVICE_ID,
|
|
client,
|
|
registration: registration(pushSubscription(() => {
|
|
unsubscribeCalls += 1
|
|
})),
|
|
})).resolves.toEqual({
|
|
browserSubscriptionRemoved: true,
|
|
serverRegistrationRemoved: true,
|
|
})
|
|
expect(unsubscribeCalls).toBe(1)
|
|
})
|
|
|
|
test('still removes the browser subscription when server cleanup fails', async () => {
|
|
let unsubscribeCalls = 0
|
|
const client = {
|
|
rpc: async () => ({ data: null, error: { message: 'offline' } }),
|
|
} as unknown as WebClient
|
|
|
|
const operation = unsubscribeWebPush({
|
|
deviceId: DEVICE_ID,
|
|
client,
|
|
registration: registration(pushSubscription(() => {
|
|
unsubscribeCalls += 1
|
|
})),
|
|
})
|
|
await expect(operation).rejects.toMatchObject({
|
|
name: 'WebPushError',
|
|
code: 'persistence-failed',
|
|
})
|
|
expect(unsubscribeCalls).toBe(1)
|
|
})
|
|
|
|
test('removes the local subscription and bounds a hung unregister RPC', async () => {
|
|
let unsubscribeCalls = 0
|
|
const client = {
|
|
rpc: () => new Promise<never>(() => undefined),
|
|
} as unknown as WebClient
|
|
|
|
await expect(unsubscribeWebPush({
|
|
deviceId: DEVICE_ID,
|
|
client,
|
|
registration: registration(pushSubscription(() => {
|
|
unsubscribeCalls += 1
|
|
})),
|
|
remoteTimeoutMs: 25,
|
|
})).rejects.toMatchObject({ code: 'persistence-failed' })
|
|
expect(unsubscribeCalls).toBe(1)
|
|
})
|
|
|
|
test('keeps disabled intent when server cleanup succeeds but local unsubscribe fails', async () => {
|
|
const storage = memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
})
|
|
const client = activeDeviceClient(async () => ({
|
|
data: { device_id: DEVICE_ID, removed: true },
|
|
error: null,
|
|
}))
|
|
|
|
await expect(disableCurrentWebPush(USER_ID, {
|
|
client,
|
|
storage,
|
|
registration: registration(pushSubscription(
|
|
undefined,
|
|
new Error('browser unsubscribe failed'),
|
|
)),
|
|
})).rejects.toMatchObject({ code: 'unsubscribe-failed' })
|
|
|
|
expect(storage.getItem(`d3ro.voice.web-push.disabled.v1.${USER_ID}`)).toBe('1')
|
|
})
|
|
|
|
test('starts local cleanup even when the device lookup never resolves', async () => {
|
|
let unsubscribeCalls = 0
|
|
const stalledChain = {
|
|
select: () => stalledChain,
|
|
eq: () => stalledChain,
|
|
maybeSingle: () => new Promise<never>(() => undefined),
|
|
}
|
|
const client = {
|
|
from: () => stalledChain,
|
|
} as unknown as WebClient
|
|
|
|
await expect(disableCurrentWebPush(USER_ID, {
|
|
client,
|
|
storage: memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
}),
|
|
registration: registration(pushSubscription(() => {
|
|
unsubscribeCalls += 1
|
|
})),
|
|
remoteCleanupTimeoutMs: 25,
|
|
})).rejects.toMatchObject({ code: 'persistence-failed' })
|
|
expect(unsubscribeCalls).toBe(1)
|
|
})
|
|
|
|
test('does not report a stale local subscription as connected after disable intent', async () => {
|
|
let rpcCalls = 0
|
|
const restore = installPushBrowser('granted', async () => 'granted')
|
|
try {
|
|
const storage = memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
[`d3ro.voice.web-push.disabled.v1.${USER_ID}`]: '1',
|
|
})
|
|
const client = activeDeviceClient(async () => {
|
|
rpcCalls += 1
|
|
return { data: null, error: null }
|
|
})
|
|
|
|
await expect(getCurrentWebPushConnectionStatus(USER_ID, {
|
|
client,
|
|
storage,
|
|
vapidPublicKey: VAPID_KEY,
|
|
registration: registration(pushSubscription()),
|
|
})).resolves.toBe('orphaned')
|
|
expect(rpcCalls).toBe(0)
|
|
} finally {
|
|
restore()
|
|
}
|
|
})
|
|
|
|
test('re-registers an existing browser subscription before reporting it connected', async () => {
|
|
const calls: Array<{ name: string; args: unknown }> = []
|
|
const restore = installPushBrowser('granted', async () => 'granted')
|
|
try {
|
|
const subscription = pushSubscription()
|
|
const client = activeDeviceClient(async (name, args) => {
|
|
calls.push({ name, args })
|
|
return {
|
|
data: { registered_at: '2026-11-04T00:00:00.000Z' },
|
|
error: null,
|
|
}
|
|
})
|
|
|
|
await expect(getCurrentWebPushConnectionStatus(USER_ID, {
|
|
client,
|
|
storage: memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
}),
|
|
vapidPublicKey: VAPID_KEY,
|
|
registration: registration(subscription),
|
|
})).resolves.toBe('subscribed')
|
|
expect(calls).toEqual([{
|
|
name: 'register_push_registration',
|
|
args: {
|
|
push_device_id: DEVICE_ID,
|
|
push_provider: 'webpush',
|
|
registration_id: JSON.stringify(subscription.toJSON()),
|
|
},
|
|
}])
|
|
} finally {
|
|
restore()
|
|
}
|
|
})
|
|
|
|
test('fails closed when an existing browser subscription cannot be re-registered', async () => {
|
|
const restore = installPushBrowser('granted', async () => 'granted')
|
|
try {
|
|
const client = activeDeviceClient(async () => ({
|
|
data: null,
|
|
error: { message: 'database unavailable' },
|
|
}))
|
|
await expect(getCurrentWebPushConnectionStatus(USER_ID, {
|
|
client,
|
|
storage: memoryStorage({
|
|
'd3ro.voice.web.installation-id.v1': DEVICE_ID,
|
|
}),
|
|
vapidPublicKey: VAPID_KEY,
|
|
registration: registration(pushSubscription()),
|
|
})).rejects.toMatchObject({ code: 'persistence-failed' })
|
|
} finally {
|
|
restore()
|
|
}
|
|
})
|
|
|
|
test('keeps the switch checked when failed enable reconciliation finds a live registration', () => {
|
|
expect(reconcileFailedWebPushEnable('subscribed')).toEqual({
|
|
enabled: true,
|
|
status: 'error',
|
|
})
|
|
expect(reconcileFailedWebPushEnable('unsubscribed')).toEqual({
|
|
enabled: false,
|
|
status: 'unsubscribed',
|
|
})
|
|
})
|
|
|
|
test('does not make sign-out wait for stalled Web Push cleanup', async () => {
|
|
let signOutCalls = 0
|
|
const stalledCleanup = new Promise<void>(() => undefined)
|
|
|
|
await expect(signOutWithoutWaitingForWebPushCleanup(
|
|
() => stalledCleanup,
|
|
async () => {
|
|
signOutCalls += 1
|
|
},
|
|
)).resolves.toBeUndefined()
|
|
expect(signOutCalls).toBe(1)
|
|
})
|
|
})
|