chore: land in-progress workspace changes before 1.16.2

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.
This commit is contained in:
Yun Chan 2026-11-05 21:58:44 +09:00
parent 9c2b6a9782
commit 7fe49c437e
144 changed files with 3760 additions and 4523 deletions

View file

@ -159,7 +159,7 @@ export default function LoginPage(): React.ReactElement {
color: d3roPalette.text.label
}}
>
{t('login.subtitle') ?? 'Precision Voice Intelligence'}
{t('login.subtitle')}
</Box>
</Box>
@ -215,7 +215,7 @@ export default function LoginPage(): React.ReactElement {
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z" />
</svg>
{t('login.google') ?? 'Google로 로그인'}
{t('login.google')}
</Box>
{/* Apple Button */}
@ -289,7 +289,7 @@ export default function LoginPage(): React.ReactElement {
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
{t('login.github') ?? 'GitHub로 로그인'}
{t('login.github')}
</Box>
</Stack>
@ -304,7 +304,7 @@ export default function LoginPage(): React.ReactElement {
letterSpacing: 0
}}
>
{t('login.or') ?? '또는'}
{t('login.or')}
</Box>
<Box sx={{ flex: 1, height: '1px', bgcolor: d3roPalette.border.default }} />
</Box>

View file

@ -1,83 +0,0 @@
'use client'
// apps/web/src/components/dashboard/meetings-trend-chart.tsx
// recharts 기반 회의/문서 추이 차트 (최근 14일).
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
Tooltip,
CartesianGrid,
Legend
} from 'recharts'
import { Box } from '@mui/material'
import { d3roPalette } from '@d3ro/ui/theme'
export interface TrendPoint {
date: string
meetings: number
documents: number
}
interface MeetingsTrendChartProps {
points: TrendPoint[]
}
export function MeetingsTrendChart({ points }: MeetingsTrendChartProps): React.ReactElement {
return (
<Box sx={{ width: '100%', height: 260 }}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={points} margin={{ top: 5, right: 12, left: -12, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke={d3roPalette.border.subtle} />
<XAxis
dataKey="date"
stroke={d3roPalette.text.muted}
fontSize={11}
tickLine={false}
/>
<YAxis
stroke={d3roPalette.text.muted}
fontSize={11}
tickLine={false}
allowDecimals={false}
/>
<Tooltip
contentStyle={{
backgroundColor: d3roPalette.bg.elevated,
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: 8,
color: d3roPalette.text.primary,
fontSize: 12
}}
labelStyle={{ color: d3roPalette.text.label }}
/>
<Legend
wrapperStyle={{ fontSize: 11, color: d3roPalette.text.secondary }}
iconType="circle"
/>
<Line
type="monotone"
dataKey="meetings"
name="Meetings"
stroke={d3roPalette.accent.main}
strokeWidth={2}
dot={{ r: 3 }}
activeDot={{ r: 5 }}
/>
<Line
type="monotone"
dataKey="documents"
name="Documents"
stroke={d3roPalette.tag.purple}
strokeWidth={2}
dot={{ r: 3 }}
activeDot={{ r: 5 }}
/>
</LineChart>
</ResponsiveContainer>
</Box>
)
}

View file

@ -31,7 +31,14 @@ import { PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import {
disableCurrentWebPush,
signOutWithoutWaitingForWebPushCleanup,
WEB_APP_VERSION,
} from '@/lib/web-push-session'
import { useAuth } from '@/components/providers/auth-provider'
import { AVAILABLE_MODES, useThemeMode } from '@/components/providers/theme-mode-context'
import { WebPushControl } from './web-push-control'
interface NavItem {
key: string
@ -45,6 +52,7 @@ export function Sidebar(): React.ReactElement {
const pathname = usePathname()
const { t } = useI18n()
const { mode, setMode } = useThemeMode()
const { user } = useAuth()
const handleThemeChange = (event: SelectChangeEvent<ThemeMode>): void => {
setMode(event.target.value as ThemeMode)
@ -54,51 +62,60 @@ export function Sidebar(): React.ReactElement {
{
key: 'dashboard',
path: '/dashboard',
label: t('nav.dashboard') ?? '대시보드',
label: t('nav.dashboard'),
icon: <DashboardIcon />
},
{
key: 'record',
path: '/record',
label: t('nav.record') ?? '실시간 녹음',
label: t('nav.record'),
icon: <MicIcon />
},
{
key: 'history',
path: '/history',
label: t('nav.history') ?? '전사 히스토리',
label: t('nav.history'),
icon: <HistoryIcon />
},
{
key: 'chat',
path: '/chat',
label: t('nav.chat') ?? '음성 대화',
label: t('nav.chat'),
icon: <ChatIcon />
},
{
key: 'dictionary',
path: '/dictionary',
label: t('nav.dictionary') ?? '커스텀 사전',
label: t('nav.dictionary'),
icon: <BookIcon />
},
{
key: 'commands',
path: '/commands',
label: t('nav.commands') ?? '명령어',
label: t('nav.commands'),
icon: <AutoAwesomeIcon />
},
{
key: 'billing',
path: '/billing',
label: t('nav.billing') ?? '구독 & 업그레이드',
label: t('nav.billing'),
icon: <PaymentIcon />
}
]
async function handleLogout(): Promise<void> {
const supabase = getSupabaseBrowserClient()
await supabase.auth.signOut()
router.replace('/login')
const cleanup = user
? () => disableCurrentWebPush(user.id, { client: supabase })
: async () => undefined
try {
await signOutWithoutWaitingForWebPushCleanup(
cleanup,
() => supabase.auth.signOut(),
)
} finally {
router.replace('/login')
}
}
return (
@ -139,7 +156,7 @@ export function Sidebar(): React.ReactElement {
</PhosphorText>
</Box>
<Box sx={{ fontSize: '11px', fontFamily: 'var(--d3-font-mono)', color: d3roPalette.text.muted }}>
v1.16.1
v{WEB_APP_VERSION}
</Box>
</Box>
@ -176,6 +193,8 @@ export function Sidebar(): React.ReactElement {
})}
</List>
<WebPushControl />
<Box sx={{ px: 2, py: 1.5, borderTop: `1px solid ${d3roPalette.border.default}` }}>
<FormControl fullWidth size="small">
<InputLabel
@ -183,18 +202,18 @@ export function Sidebar(): React.ReactElement {
sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}
>
<PaletteIcon fontSize="inherit" />
{t('theme.label') ?? 'Theme'}
{t('theme.label')}
</InputLabel>
<Select<ThemeMode>
labelId="theme-mode-label"
id="theme-mode-select"
value={mode}
onChange={handleThemeChange}
label={t('theme.label') ?? 'Theme'}
label={t('theme.label')}
>
{AVAILABLE_MODES.map((m) => (
<MenuItem key={m} value={m}>
{t(`theme.${m}`) ?? m}
{t(`theme.${m}`)}
</MenuItem>
))}
</Select>
@ -208,7 +227,7 @@ export function Sidebar(): React.ReactElement {
<LogoutIcon />
</ListItemIcon>
<ListItemText
primary={t('nav.logout') ?? '로그아웃'}
primary={t('nav.logout')}
primaryTypographyProps={{ fontSize: 13, color: d3roPalette.text.secondary }}
/>
</ListItemButton>

View file

@ -0,0 +1,209 @@
'use client'
import { useEffect, useState } from 'react'
import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone'
import { Box, Switch } from '@mui/material'
import { useI18n } from '@d3ro/i18n'
import { d3roFocusRing, d3roPalette } from '@d3ro/ui/theme'
import { useAuth } from '@/components/providers/auth-provider'
import {
disableCurrentWebPush,
enableCurrentWebPush,
getCurrentWebPushConnectionStatus,
reconcileFailedWebPushEnable,
type WebPushConnectionStatus,
} from '@/lib/web-push-session'
type ControlStatus =
| WebPushConnectionStatus
| 'checking'
| 'enabling'
| 'disabling'
| 'error'
const STATUS_MESSAGE_KEYS = {
checking: 'web.push.checking',
enabling: 'web.push.enabling',
disabling: 'web.push.disabling',
subscribed: 'web.push.enabled',
unsubscribed: 'web.push.disabled',
unsupported: 'web.push.unsupported',
unconfigured: 'web.push.unconfigured',
blocked: 'web.push.blocked',
orphaned: 'web.push.disabled',
revoked: 'web.push.revoked',
error: 'web.push.error',
} as const
function isBusy(status: ControlStatus): boolean {
return status === 'checking' || status === 'enabling' || status === 'disabling'
}
function isUnavailable(status: ControlStatus): boolean {
return status === 'unsupported'
|| status === 'unconfigured'
|| status === 'blocked'
|| status === 'revoked'
}
export function WebPushControl(): React.ReactElement {
const { t } = useI18n()
const { user } = useAuth()
const [status, setStatus] = useState<ControlStatus>('checking')
const [enabled, setEnabled] = useState(false)
const userId = user?.id
useEffect(() => {
let active = true
if (!userId) {
setEnabled(false)
setStatus('checking')
return () => {
active = false
}
}
void getCurrentWebPushConnectionStatus(userId)
.then(async (nextStatus) => {
if (!active) return
if (nextStatus === 'orphaned' || nextStatus === 'revoked') {
try {
await disableCurrentWebPush(userId)
} catch {
if (active) setStatus('error')
return
}
}
if (!active) return
setEnabled(nextStatus === 'subscribed')
setStatus(nextStatus === 'orphaned' ? 'unsubscribed' : nextStatus)
})
.catch(() => {
if (active) setStatus('error')
})
return () => {
active = false
}
}, [userId])
async function handleToggle(shouldEnable: boolean): Promise<void> {
if (!userId || isBusy(status) || isUnavailable(status)) return
if (shouldEnable) {
setStatus('enabling')
try {
await enableCurrentWebPush(userId)
setEnabled(true)
setStatus('subscribed')
} catch {
try {
const current = await getCurrentWebPushConnectionStatus(userId)
const reconciled = reconcileFailedWebPushEnable(current)
setEnabled(reconciled.enabled)
setStatus(reconciled.status)
} catch {
setEnabled(false)
setStatus('error')
}
}
return
}
setStatus('disabling')
try {
await disableCurrentWebPush(userId)
setEnabled(false)
setStatus('unsubscribed')
} catch {
try {
const current = await getCurrentWebPushConnectionStatus(userId)
setEnabled(current === 'subscribed')
} catch {
setEnabled(false)
}
setStatus('error')
}
}
const disabled = !userId || isBusy(status) || isUnavailable(status)
const isError = status === 'error' || status === 'revoked'
return (
<Box sx={{ px: 2, py: 1.5, borderTop: `1px solid ${d3roPalette.border.default}` }}>
<Box sx={{ minHeight: 44, display: 'flex', alignItems: 'center', gap: 1 }}>
<NotificationsNoneIcon
aria-hidden="true"
sx={{ width: 20, height: 20, color: d3roPalette.text.label }}
/>
<Box
id="web-push-label"
sx={{ flex: 1, color: d3roPalette.text.secondary, fontSize: 13 }}
>
{t('web.push.label')}
</Box>
<Box
component="label"
htmlFor="web-push-toggle"
sx={{
width: 44,
height: 44,
flexShrink: 0,
display: 'grid',
placeItems: 'center',
cursor: disabled ? 'not-allowed' : 'pointer',
}}
>
<Switch
id="web-push-toggle"
size="small"
checked={enabled}
disabled={disabled}
onChange={(_event, checked) => void handleToggle(checked)}
sx={{
width: 44,
height: 44,
p: '17px 9px',
'& .MuiSwitch-switchBase': {
top: 10,
left: 2,
},
'& .MuiSwitch-input': {
top: -10,
left: -2,
width: 44,
height: 44,
},
'& .MuiSwitch-switchBase.Mui-checked .MuiSwitch-input': {
transform: 'translateX(-16px)',
},
'& .MuiSwitch-switchBase.Mui-focusVisible': d3roFocusRing,
}}
slotProps={{
input: {
role: 'switch',
'aria-labelledby': 'web-push-label',
'aria-describedby': 'web-push-status',
},
}}
/>
</Box>
</Box>
<Box
id="web-push-status"
role="status"
aria-live="polite"
aria-atomic="true"
sx={{
minHeight: 32,
mt: 0.5,
color: isError ? d3roPalette.status.danger : d3roPalette.text.muted,
fontSize: 11,
lineHeight: 1.45,
}}
>
{t(STATUS_MESSAGE_KEYS[status])}
</Box>
</Box>
)
}

View file

@ -0,0 +1,267 @@
'use client'
// apps/web/src/lib/web-device.ts
// Browser installation identity + active Supabase device registration for Web Push.
import { getSupabaseBrowserClient } from './supabase-browser'
type WebDeviceClient = ReturnType<typeof getSupabaseBrowserClient>
type StorageAdapter = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
export type WebDeviceErrorCode =
| 'auth'
| 'unsupported-browser'
| 'storage-unavailable'
| 'invalid-response'
| 'device-revoked'
| 'server'
export class WebDeviceError extends Error {
constructor(
public readonly code: WebDeviceErrorCode,
message: string,
) {
super(message)
this.name = 'WebDeviceError'
}
}
export interface WebDeviceRegistration {
id: string
installationId: string
revokedAt: string | null
}
export interface WebDeviceEnvironment {
client?: WebDeviceClient
storage?: StorageAdapter
uuidFactory?: () => string
now?: () => Date
deviceName?: string
osVersion?: string | null
}
const INSTALLATION_ID_KEY = 'd3ro.voice.web.installation-id.v1'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
function requireUserId(userId: string): void {
if (!UUID_PATTERN.test(userId)) {
throw new WebDeviceError('auth', 'A valid authenticated user ID is required')
}
}
function requireStorage(override?: StorageAdapter): StorageAdapter {
if (override) return override
if (typeof window === 'undefined') {
throw new WebDeviceError('unsupported-browser', 'Browser storage is unavailable')
}
try {
return window.localStorage
} catch {
throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
}
}
function createInstallationId(override?: () => string): string {
const generated = override?.()
?? (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: null)
if (!generated || !UUID_PATTERN.test(generated)) {
throw new WebDeviceError('unsupported-browser', 'Secure browser identity generation is unavailable')
}
return generated
}
export function getStoredWebInstallationId(storageOverride?: StorageAdapter): string | null {
const storage = requireStorage(storageOverride)
try {
const stored = storage.getItem(INSTALLATION_ID_KEY)
if (!stored) return null
if (UUID_PATTERN.test(stored)) return stored
storage.removeItem(INSTALLATION_ID_KEY)
return null
} catch {
throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
}
}
export function getOrCreateWebInstallationId(
storageOverride?: StorageAdapter,
uuidFactory?: () => string,
): string {
const storage = requireStorage(storageOverride)
const existing = getStoredWebInstallationId(storage)
if (existing) return existing
const installationId = createInstallationId(uuidFactory)
try {
storage.setItem(INSTALLATION_ID_KEY, installationId)
} catch {
throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
}
return installationId
}
export function describeWebBrowserDevice(
userAgent: string,
platform: string,
): { deviceName: string; osVersion: string | null } {
const browser = /Edg\//.test(userAgent)
? 'Microsoft Edge'
: /Firefox\//.test(userAgent)
? 'Firefox'
: /Chrome\//.test(userAgent)
? 'Chrome'
: /Safari\//.test(userAgent)
? 'Safari'
: 'Web browser'
const os = /Windows/.test(userAgent)
? 'Windows'
: /Android/.test(userAgent)
? 'Android'
: /iPhone|iPad|iPod/.test(userAgent)
? 'iOS'
: /Macintosh|Mac OS/.test(userAgent)
? 'macOS'
: /Linux/.test(userAgent)
? 'Linux'
: platform.trim() || 'Web'
return {
deviceName: `${browser} · ${os}`.slice(0, 120),
osVersion: platform.trim().slice(0, 120) || null,
}
}
function defaultDeviceMetadata(): { deviceName: string; osVersion: string | null } {
if (typeof navigator === 'undefined') {
throw new WebDeviceError('unsupported-browser', 'Browser metadata is unavailable')
}
return describeWebBrowserDevice(navigator.userAgent, navigator.platform)
}
function parseDevice(
value: unknown,
installationId: string,
): WebDeviceRegistration {
if (typeof value !== 'object' || value === null) {
throw new WebDeviceError('invalid-response', 'The device response is invalid')
}
const row = value as Record<string, unknown>
if (
typeof row.id !== 'string'
|| (row.revoked_at !== null && typeof row.revoked_at !== 'string')
) {
throw new WebDeviceError('invalid-response', 'The device response is invalid')
}
return {
id: row.id,
installationId,
revokedAt: row.revoked_at,
}
}
async function readDevice(
client: WebDeviceClient,
userId: string,
installationId: string,
): Promise<WebDeviceRegistration | null> {
const result = await client
.from('devices')
.select('id,revoked_at')
.eq('user_id', userId)
.eq('installation_id', installationId)
.maybeSingle()
if (result.error) {
throw new WebDeviceError('server', result.error.message)
}
return result.data ? parseDevice(result.data, installationId) : null
}
export async function findCurrentWebDevice(
userId: string,
environment: WebDeviceEnvironment = {},
): Promise<WebDeviceRegistration | null> {
requireUserId(userId)
const installationId = getStoredWebInstallationId(environment.storage)
if (!installationId) return null
const client = environment.client ?? getSupabaseBrowserClient()
return readDevice(client, userId, installationId)
}
export async function ensureCurrentWebDevice(
userId: string,
appVersion: string,
environment: WebDeviceEnvironment = {},
): Promise<WebDeviceRegistration> {
requireUserId(userId)
if (!appVersion.trim()) {
throw new WebDeviceError('invalid-response', 'A valid app version is required')
}
const client = environment.client ?? getSupabaseBrowserClient()
const installationId = getOrCreateWebInstallationId(
environment.storage,
environment.uuidFactory,
)
const metadata = environment.deviceName
? {
deviceName: environment.deviceName.slice(0, 120),
osVersion: environment.osVersion?.slice(0, 120) ?? null,
}
: defaultDeviceMetadata()
const nowIso = (environment.now?.() ?? new Date()).toISOString()
const existing = await readDevice(client, userId, installationId)
if (existing?.revokedAt) {
throw new WebDeviceError('device-revoked', 'This browser registration has been revoked')
}
if (existing) {
const updated = await client
.from('devices')
.update({
device_name: metadata.deviceName,
app_version: appVersion.trim(),
os_version: metadata.osVersion,
last_seen_at: nowIso,
})
.eq('user_id', userId)
.eq('id', existing.id)
.is('revoked_at', null)
.select('id,revoked_at')
.maybeSingle()
if (updated.error) {
throw new WebDeviceError('server', updated.error.message)
}
if (!updated.data) {
throw new WebDeviceError('device-revoked', 'This browser registration is no longer active')
}
return parseDevice(updated.data, installationId)
}
const inserted = await client
.from('devices')
.insert({
user_id: userId,
installation_id: installationId,
platform: 'web',
device_name: metadata.deviceName,
app_version: appVersion.trim(),
os_version: metadata.osVersion,
last_seen_at: nowIso,
})
.select('id,revoked_at')
.single()
if (inserted.error) {
if (inserted.error.code === '23505') {
const concurrent = await readDevice(client, userId, installationId)
if (concurrent?.revokedAt) {
throw new WebDeviceError('device-revoked', 'This browser registration has been revoked')
}
if (concurrent) return concurrent
}
throw new WebDeviceError('server', inserted.error.message)
}
return parseDevice(inserted.data, installationId)
}

View file

@ -0,0 +1,195 @@
'use client'
// apps/web/src/lib/web-push-session.ts
// One production orchestration boundary for browser device + Web Push state.
import webPackage from '../../package.json'
import {
ensureCurrentWebDevice,
findCurrentWebDevice,
type WebDeviceEnvironment,
} from './web-device'
import {
getWebPushBrowserStatus,
registerExistingWebPushSubscription,
requestWebPushPermission,
subscribeWebPush,
unsubscribeBrowserWebPush,
unregisterWebPushServer,
WebPushError,
type WebPushBrowserStatus,
} from './web-push'
export type WebPushConnectionStatus =
| WebPushBrowserStatus
| 'orphaned'
| 'revoked'
export interface WebPushSessionEnvironment extends WebDeviceEnvironment {
vapidPublicKey?: string
registration?: ServiceWorkerRegistration | null
remoteCleanupTimeoutMs?: number
}
export const WEB_APP_VERSION = webPackage.version
const DISABLED_INTENT_KEY_PREFIX = 'd3ro.voice.web-push.disabled.v1.'
const DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS = 5_000
export function reconcileFailedWebPushEnable(
currentStatus: WebPushConnectionStatus,
): { enabled: boolean; status: WebPushConnectionStatus | 'error' } {
const enabled = currentStatus === 'subscribed'
return {
enabled,
status: enabled ? 'error' : currentStatus,
}
}
export async function signOutWithoutWaitingForWebPushCleanup(
cleanup: () => Promise<void>,
signOut: () => Promise<unknown>,
): Promise<void> {
try {
void cleanup().catch(() => undefined)
} catch {
// Cleanup is best effort. Logout remains independently available.
}
await signOut()
}
function withSessionCleanupTimeout<T>(
operation: Promise<T>,
timeoutMs: number,
): Promise<T> {
const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
? timeoutMs
: DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new WebPushError(
'persistence-failed',
'Timed out while resolving the server Web Push registration',
))
}, boundedTimeoutMs)
operation.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error: unknown) => {
clearTimeout(timer)
reject(error)
},
)
})
}
function disabledIntentKey(userId: string): string {
return `${DISABLED_INTENT_KEY_PREFIX}${userId}`
}
function sessionStorage(environment: WebPushSessionEnvironment): Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> {
if (environment.storage) return environment.storage
if (typeof window === 'undefined') {
throw new Error('Browser storage is unavailable')
}
return window.localStorage
}
function hasDisabledIntent(userId: string, environment: WebPushSessionEnvironment): boolean {
return sessionStorage(environment).getItem(disabledIntentKey(userId)) === '1'
}
function recordDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void {
sessionStorage(environment).setItem(disabledIntentKey(userId), '1')
}
function clearDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void {
sessionStorage(environment).removeItem(disabledIntentKey(userId))
}
export async function getCurrentWebPushConnectionStatus(
userId: string,
environment: WebPushSessionEnvironment = {},
): Promise<WebPushConnectionStatus> {
const browserStatus = await getWebPushBrowserStatus(
environment.vapidPublicKey,
undefined,
environment.registration,
)
if (browserStatus !== 'subscribed') return browserStatus
if (hasDisabledIntent(userId, environment)) return 'orphaned'
const device = await findCurrentWebDevice(userId, environment)
if (!device) return 'orphaned'
if (device.revokedAt) return 'revoked'
// A local PushSubscription is not proof that its server token still exists.
// Re-registering is idempotent and makes the server RPC the authority before
// the UI can report that Web Push is connected.
await registerExistingWebPushSubscription({
userId,
deviceId: device.id,
client: environment.client,
registration: environment.registration,
})
return 'subscribed'
}
export async function enableCurrentWebPush(
userId: string,
environment: WebPushSessionEnvironment = {},
): Promise<void> {
// Invoke the permission prompt before any network await so this call still
// carries the user's transient activation from the sidebar switch gesture.
await requestWebPushPermission(environment.vapidPublicKey)
const device = await ensureCurrentWebDevice(userId, WEB_APP_VERSION, environment)
await subscribeWebPush({
userId,
deviceId: device.id,
vapidPublicKey: environment.vapidPublicKey,
client: environment.client,
registration: environment.registration ?? undefined,
})
clearDisabledIntent(userId, environment)
}
export async function disableCurrentWebPush(
userId: string,
environment: WebPushSessionEnvironment = {},
): Promise<void> {
let intentFailure: unknown
try {
// Record intent before either remote or local cleanup. If local unsubscribe
// fails, the next load stays fail-closed and retries cleanup instead of
// treating the stale browser subscription as connected.
recordDisabledIntent(userId, environment)
} catch (error) {
intentFailure = error
}
const browserCleanup = unsubscribeBrowserWebPush({
registration: environment.registration,
})
const remoteCleanupOperation = (async () => {
const device = await findCurrentWebDevice(userId, environment)
if (!device) return false
return unregisterWebPushServer({
deviceId: device.id,
client: environment.client,
timeoutMs: environment.remoteCleanupTimeoutMs,
})
})()
const remoteCleanup = withSessionCleanupTimeout(
remoteCleanupOperation,
environment.remoteCleanupTimeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS,
)
const [browserResult, remoteResult] = await Promise.allSettled([
browserCleanup,
remoteCleanup,
])
if (browserResult.status === 'rejected') throw browserResult.reason
if (remoteResult.status === 'rejected') throw remoteResult.reason
if (intentFailure) throw intentFailure
}

View file

@ -1,9 +1,10 @@
// apps/web/src/lib/web-push.ts
// D3RO Voice — Web Push Service Worker Registration & VAPID Subscription
import type { SupabaseClient } from '@supabase/supabase-js'
import { getSupabaseBrowserClient } from './supabase-browser'
type WebPushClient = ReturnType<typeof getSupabaseBrowserClient>
export type WebPushProvider = 'webpush'
export type WebPushErrorCode =
@ -13,6 +14,7 @@ export type WebPushErrorCode =
| 'vapid-key-missing'
| 'invalid-vapid-key'
| 'subscription-failed'
| 'unsubscribe-failed'
| 'persistence-failed'
export class WebPushError extends Error {
@ -34,16 +36,60 @@ export interface WebPushSubscriptionRecord {
export interface SubscribeWebPushOptions {
userId: string
deviceId?: string
deviceId: string
vapidPublicKey?: string
serviceWorkerPath?: string
serviceWorkerScope?: string
client?: SupabaseClient
client?: WebPushClient
registration?: ServiceWorkerRegistration
}
export interface UnsubscribeWebPushOptions {
deviceId?: string
serviceWorkerScope?: string
client?: WebPushClient
registration?: ServiceWorkerRegistration | null
remoteTimeoutMs?: number
}
export interface UnsubscribeBrowserWebPushOptions {
serviceWorkerScope?: string
registration?: ServiceWorkerRegistration | null
}
export interface UnregisterWebPushServerOptions {
deviceId: string
client?: WebPushClient
timeoutMs?: number
}
export interface RegisterExistingWebPushOptions {
userId: string
deviceId: string
serviceWorkerScope?: string
client?: WebPushClient
registration?: ServiceWorkerRegistration | null
}
export type WebPushBrowserStatus =
| 'unsupported'
| 'unconfigured'
| 'blocked'
| 'unsubscribed'
| 'subscribed'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const DEFAULT_SW_PATH = '/app/sw.js'
const DEFAULT_SW_SCOPE = '/app/'
const DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS = 5_000
function browserSupportsWebPush(): boolean {
return typeof window !== 'undefined'
&& typeof navigator !== 'undefined'
&& typeof Notification !== 'undefined'
&& 'serviceWorker' in navigator
&& 'PushManager' in window
}
export function getVapidPublicKey(overrideKey?: string): string | null {
const candidate = (overrideKey ?? process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? '').trim()
@ -74,22 +120,96 @@ export async function registerWebPushServiceWorker(
if (
typeof window === 'undefined'
|| typeof navigator === 'undefined'
|| !('serviceWorker' in navigator)
|| !('PushManager' in window)
|| !browserSupportsWebPush()
) {
throw new WebPushError('unsupported-browser', 'Web Push is not supported in this browser')
}
return navigator.serviceWorker.register(serviceWorkerPath, { scope })
}
export async function getWebPushBrowserStatus(
vapidPublicKey?: string,
serviceWorkerScope = DEFAULT_SW_SCOPE,
registrationOverride?: ServiceWorkerRegistration | null,
): Promise<WebPushBrowserStatus> {
if (!browserSupportsWebPush()) return 'unsupported'
if (!getVapidPublicKey(vapidPublicKey)) return 'unconfigured'
if (Notification.permission === 'denied') return 'blocked'
const registration = registrationOverride !== undefined
? registrationOverride
: await navigator.serviceWorker.getRegistration(serviceWorkerScope)
if (!registration) return 'unsubscribed'
const subscription = await registration.pushManager.getSubscription()
return subscription ? 'subscribed' : 'unsubscribed'
}
async function persistWebPushSubscription(
subscription: PushSubscription,
deviceId: string,
client?: WebPushClient,
): Promise<WebPushSubscriptionRecord> {
const serialized = JSON.stringify(subscription.toJSON())
const supabase = client ?? getSupabaseBrowserClient()
const nowIso = new Date().toISOString()
let result: Awaited<ReturnType<typeof supabase.rpc>>
try {
result = await supabase.rpc('register_push_registration', {
push_device_id: deviceId,
push_provider: 'webpush',
registration_id: serialized,
})
} catch (error) {
throw new WebPushError(
'persistence-failed',
error instanceof Error ? error.message : 'Failed to persist the Web Push registration',
)
}
if (result.error) {
throw new WebPushError('persistence-failed', result.error.message)
}
const record = typeof result.data === 'object' && result.data !== null
? (result.data as Record<string, unknown>)
: null
const registeredAt = typeof record?.registered_at === 'string'
? record.registered_at
: nowIso
return {
provider: 'webpush',
endpoint: subscription.endpoint,
subscriptionJson: serialized,
registeredAt,
}
}
export async function requestWebPushPermission(vapidPublicKey?: string): Promise<void> {
if (!browserSupportsWebPush()) {
throw new WebPushError('unsupported-browser', 'Web Push is not supported in this browser')
}
if (!getVapidPublicKey(vapidPublicKey)) {
throw new WebPushError('vapid-key-missing', 'NEXT_PUBLIC_VAPID_PUBLIC_KEY is not configured')
}
if (Notification.permission === 'denied') {
throw new WebPushError('permission-denied', 'Notification permission has been denied')
}
if (Notification.permission === 'default') {
const permission = await Notification.requestPermission()
if (permission !== 'granted') {
throw new WebPushError('permission-denied', 'Notification permission was not granted')
}
}
}
export async function subscribeWebPush(
options: SubscribeWebPushOptions,
): Promise<WebPushSubscriptionRecord> {
if (!UUID_PATTERN.test(options.userId)) {
throw new WebPushError('auth', 'A valid authenticated user ID is required for Web Push')
}
if (options.deviceId !== undefined && !UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid device ID is required when binding Web Push to a device')
if (!UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
}
const vapidPublicKey = getVapidPublicKey(options.vapidPublicKey)
@ -103,7 +223,7 @@ export async function subscribeWebPush(
throw new WebPushError('permission-denied', 'Notification permission has been denied')
}
const registration = await registerWebPushServiceWorker(
const registration = options.registration ?? await registerWebPushServiceWorker(
options.serviceWorkerPath ?? DEFAULT_SW_PATH,
options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
)
@ -122,54 +242,163 @@ export async function subscribeWebPush(
)
}
const serialized = JSON.stringify(subscription.toJSON())
const supabase = options.client ?? getSupabaseBrowserClient()
const nowIso = new Date().toISOString()
if (options.deviceId) {
const { data, error } = await supabase.rpc('register_push_registration', {
push_device_id: options.deviceId,
push_provider: 'webpush',
registration_id: serialized,
})
if (error) {
throw new WebPushError('persistence-failed', error.message)
try {
return await persistWebPushSubscription(subscription, options.deviceId, options.client)
} catch (error) {
try {
await subscription.unsubscribe()
} catch {
// The persistence failure remains authoritative. A later disable/logout
// path retries local cleanup before the session is closed.
}
const record = typeof data === 'object' && data !== null
? (data as Record<string, unknown>)
: null
const registeredAt = typeof record?.registered_at === 'string'
? record.registered_at
: nowIso
return {
provider: 'webpush',
endpoint: subscription.endpoint,
subscriptionJson: serialized,
registeredAt,
}
}
const { error } = await supabase
.from('push_tokens')
.upsert(
{
user_id: options.userId,
token: serialized,
platform: 'web',
provider: 'webpush',
updated_at: nowIso,
},
{ onConflict: 'user_id,token' },
)
if (error) {
throw new WebPushError('persistence-failed', error.message)
}
return {
provider: 'webpush',
endpoint: subscription.endpoint,
subscriptionJson: serialized,
registeredAt: nowIso,
throw error
}
}
export async function registerExistingWebPushSubscription(
options: RegisterExistingWebPushOptions,
): Promise<WebPushSubscriptionRecord> {
if (!UUID_PATTERN.test(options.userId)) {
throw new WebPushError('auth', 'A valid authenticated user ID is required for Web Push')
}
if (!UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
}
let subscription: PushSubscription | null
try {
const registration = options.registration !== undefined
? options.registration
: browserSupportsWebPush()
? await navigator.serviceWorker.getRegistration(
options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
)
: null
subscription = await registration?.pushManager.getSubscription() ?? null
} catch (error) {
throw new WebPushError(
'subscription-failed',
error instanceof Error ? error.message : 'Failed to read the browser Push subscription',
)
}
if (!subscription) {
throw new WebPushError('subscription-failed', 'The browser Push subscription is unavailable')
}
return persistWebPushSubscription(subscription, options.deviceId, options.client)
}
function withRemoteCleanupTimeout<T>(operation: PromiseLike<T>, timeoutMs: number): Promise<T> {
const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
? timeoutMs
: DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new WebPushError(
'persistence-failed',
'Timed out while removing the server Web Push registration',
))
}, boundedTimeoutMs)
operation.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error: unknown) => {
clearTimeout(timer)
reject(error)
},
)
})
}
export async function unregisterWebPushServer(
options: UnregisterWebPushServerOptions,
): Promise<boolean> {
if (!UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
}
const supabase = options.client ?? getSupabaseBrowserClient()
let result: Awaited<ReturnType<typeof supabase.rpc>>
try {
result = await withRemoteCleanupTimeout(
supabase.rpc('unregister_push_registration', {
push_device_id: options.deviceId,
}),
options.timeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS,
)
} catch (error) {
if (error instanceof WebPushError) throw error
throw new WebPushError(
'persistence-failed',
error instanceof Error ? error.message : 'Failed to remove the server Web Push registration',
)
}
if (result.error) {
throw new WebPushError('persistence-failed', result.error.message)
}
if (
typeof result.data === 'object'
&& result.data !== null
&& 'removed' in result.data
&& typeof result.data.removed === 'boolean'
) {
return result.data.removed
}
return false
}
export async function unsubscribeBrowserWebPush(
options: UnsubscribeBrowserWebPushOptions = {},
): Promise<boolean> {
try {
const registration = options.registration !== undefined
? options.registration
: browserSupportsWebPush()
? await navigator.serviceWorker.getRegistration(
options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
)
: null
const subscription = await registration?.pushManager.getSubscription()
return subscription ? await subscription.unsubscribe() : false
} catch (error) {
throw new WebPushError(
'unsubscribe-failed',
error instanceof Error ? error.message : 'Failed to remove the browser Push subscription',
)
}
}
export async function unsubscribeWebPush(
options: UnsubscribeWebPushOptions,
): Promise<{ browserSubscriptionRemoved: boolean; serverRegistrationRemoved: boolean }> {
if (options.deviceId && !UUID_PATTERN.test(options.deviceId)) {
throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
}
// Start both operations before awaiting either one. A hung remote RPC must
// never prevent the browser from removing its local PushSubscription.
const serverCleanup = options.deviceId
? unregisterWebPushServer({
deviceId: options.deviceId,
client: options.client,
timeoutMs: options.remoteTimeoutMs,
})
: Promise.resolve(false)
const browserCleanup = unsubscribeBrowserWebPush({
registration: options.registration,
serviceWorkerScope: options.serviceWorkerScope,
})
const [serverResult, browserResult] = await Promise.allSettled([
serverCleanup,
browserCleanup,
])
if (browserResult.status === 'rejected') throw browserResult.reason
if (serverResult.status === 'rejected') throw serverResult.reason
return {
browserSubscriptionRemoved: browserResult.value,
serverRegistrationRemoved: serverResult.value,
}
}