Merge branch 'main' into staging

This commit is contained in:
Usman
2026-02-27 13:26:49 +01:00
committed by GitHub
11 changed files with 1004 additions and 43 deletions

View File

@@ -8,7 +8,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
### Added
- **Performance insights.** Track how fast your site loads with Core Web Vitals (page load speed, layout shifts, responsiveness). Turn it on in Site Settings → Data & Privacy to see a performance widget on your dashboard.
- **App Switcher in User Menu.** Click your profile in the top right and you'll now see a "Ciphera Apps" section. Expand it to quickly jump between Pulse, Drop (file sharing), and your Ciphera Account settings. This makes it easier to discover and navigate between Ciphera products without signing in again.
- **Faster billing page loading.** Your subscription details now load much quicker when you visit the billing page. Previously, several requests to our payment provider were made one after another, which could add 1-2 seconds to the page load. Now these happen simultaneously, cutting the wait time significantly. If any request takes too long, we gracefully continue so you always see your billing information without frustrating delays.
- **Faster funnel analysis for multi-step conversions.** We've significantly improved how conversion funnels are calculated. Instead of scanning your data multiple times for each step in a funnel, we now do it in a single efficient pass. This means complex funnels with multiple steps load almost instantly instead of taking seconds—or even timing out. We've also added a reasonable limit of 5 steps per funnel to ensure optimal performance.
- **More reliable database connections under heavy load.** We've optimized how Pulse manages its database connections to handle much higher traffic without issues. By increasing the connection pool size and improving how connections are reused, your dashboard stays responsive even when thousands of users are viewing analytics simultaneously. We also added better monitoring so we can detect and address connection issues before they affect you.
- **Better support for growing teams and traffic.** We've added infrastructure improvements that allow Pulse to run smoothly across multiple servers. When you scale up to handle more traffic, our background processes—like daily analytics calculations and data cleanup—will coordinate automatically so they don't conflict with each other. This ensures reliable performance as your team and data grow.
- **Smarter protection for heavy dashboard operations.** We've implemented a new tiered rate limiting system that treats complex dashboard queries differently from simple requests. Expensive operations—like loading your full dashboard with all its charts and data—now have their own dedicated limits to prevent anyone from accidentally overwhelming the system with too many rapid refreshes. This keeps everything running smoothly for everyone, especially during busy periods.
- **Smarter caching for faster dashboard loading.** We've added intelligent caching headers to our API responses, so your browser can remember recently loaded data and show it instantly when you navigate between pages. This works alongside our existing server-side caching to make your dashboard feel even more responsive—especially when switching between different date ranges or sections.
- **More flexible uptime monitoring.** We've made our uptime checker more adaptable to different needs. Instead of a fixed limit on how many websites we can check simultaneously, you can now configure this based on your requirements. This means faster uptime checks for busy sites with many monitors, while keeping things efficient for smaller setups.
- **Smarter data cleanup for better performance.** We've improved how old analytics data is cleaned up to keep everything running smoothly. Instead of deleting large amounts of data all at once—which could slow things down—we now remove old data in small, efficient batches. This ensures your dashboard stays fast and responsive even as we clean up months of historical data behind the scenes.
- **Faster analytics processing for all sites.** We've upgraded how your daily analytics are calculated behind the scenes. Instead of processing sites one by one, we now analyze multiple sites simultaneously using a smart parallel system. This means your daily stats—like visitor counts and page views—are updated more quickly and consistently, even as we handle data from thousands of websites.
- **Lighter dashboard data transfers.** Your dashboard now loads data in smaller, focused pieces instead of one massive bundle. This means faster loading times—especially on slower connections—and your analytics appear section by section as they become ready, rather than making you wait for everything at once.
- **Smarter data fetching.** Your dashboard now automatically prevents duplicate requests when multiple components ask for the same data at the same time. It also briefly caches recent responses, so switching between pages feels instant while still keeping everything up to date. This reduces server load and makes the app feel snappier.
- **Smarter dashboard updates.** Your dashboard now knows when you're actively viewing it versus when it's in the background. When you switch to another tab, we intelligently slow down data refreshes to save resources, then instantly catch up when you return. This keeps your analytics current without putting unnecessary load on the system.
- **Instant real-time visitor counts.** Your dashboard's "current visitors" counter now updates lightning-fast using an optimized tracking system. Instead of scanning your entire database, we maintain a live session index that shows active visitors in milliseconds—even when thousands of people are browsing your sites simultaneously.
- **Faster event tracking.** Your analytics data is now captured instantly without slowing down your website. We've switched to asynchronous processing that collects events in batches of 100, so your visitors' page views and interactions are recorded with zero impact on their browsing experience, even during traffic spikes.
- **Faster dashboard loading.** Your site analytics now load almost instantly, even during busy periods. Behind the scenes, we've added intelligent caching that remembers your dashboard data for 30 seconds and refreshes it automatically in the background. Real-time visitor counts are updated every 5 seconds so you always see current activity without waiting.
- **Better data management for long-term performance.** We've restructured how your analytics data is stored so the app stays fast even as you collect months of data. Old data is now automatically organized by month and cleaned up efficiently based on your retention settings, keeping everything running smoothly no matter how much traffic you get.
- **Smarter database indexing.** We've optimized how your analytics data is indexed, making common queries—like loading your dashboard or filtering by date—significantly faster. This also reduces storage overhead, keeping the app lean as your data grows.
- **Faster dashboard statistics.** Loading stats for any date range is now much quicker. Instead of recalculating from scratch every time, we use pre-computed daily summaries so your analytics appear instantly, even for months of data.
- **Performance insights. Track how fast your site loads with Core Web Vitals (page load speed, layout shifts, responsiveness). Turn it on in Site Settings → Data & Privacy to see a performance widget on your dashboard.
- **Goals & Events.** Define custom goals (e.g. signup, purchase) and track them with `pulse.track()` in your snippet. Counts appear on your dashboard once you add goals in Site Settings → Goals & Events.
- **2FA recovery codes backup.** When you enable 2FA, you receive recovery codes. You can now regenerate new codes (with password confirmation) from Settings and download them as a `.txt` file. Regenerating invalidates all existing codes.
@@ -20,6 +39,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- **Sign in after inactivity.** Clicking "Sign in" after a period of inactivity no longer does nothing. Previously, stale refresh cookies caused the middleware to redirect away from the login page; now only a valid access token triggers that redirect, so you can complete OAuth sign-in when your session has expired.
- **Frequent re-login.** You no longer have to sign in multiple times a day. When the access token expires after 15 minutes of inactivity, the app now automatically refreshes it using your refresh token on the next page load, so you stay logged in for up to 30 days.
- **2FA disable now requires password confirmation.** Disabling 2FA sends the derived password to the backend for verification. This prevents an attacker with a hijacked session from stripping 2FA.
- **More accurate visitor tracking.** We fixed rare edge cases where visitor counts could be slightly off during busy traffic spikes. Previously, the timestamp-based session ID generation could occasionally create overlapping identifiers. Every visitor now gets a truly unique UUID that never overlaps with others, ensuring your analytics are always precise.
## [0.11.1-alpha] - 2026-02-23

View File

@@ -35,11 +35,15 @@ export type AuthExchangeErrorType = 'network' | 'expired' | 'invalid' | 'server'
export async function exchangeAuthCode(code: string, codeVerifier: string | null, redirectUri: string) {
try {
// * IMPORTANT: credentials: 'include' is required to receive httpOnly cookies from Auth API
// * The Auth API sets access_token, refresh_token, and csrf_token as httpOnly cookies
// * We must forward these to the browser for cross-subdomain auth to work
const res = await fetch(`${AUTH_API_URL}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // * Critical: receives httpOnly cookies from Auth API
body: JSON.stringify({
grant_type: 'authorization_code',
code,
@@ -91,6 +95,50 @@ export async function exchangeAuthCode(code: string, codeVerifier: string | null
maxAge: 60 * 60 * 24 * 30 // 30 days
})
// * Forward cookies from Auth API response to browser
// * The Auth API sets httpOnly cookies on auth.ciphera.net - we need to mirror them on pulse.ciphera.net
const setCookieHeaders = res.headers.getSetCookie()
if (setCookieHeaders && setCookieHeaders.length > 0) {
for (const cookieStr of setCookieHeaders) {
// * Parse Set-Cookie header (format: name=value; attributes...)
const [nameValue] = cookieStr.split(';')
const [name, value] = nameValue.trim().split('=')
if (name && value) {
// * Determine if httpOnly (default true for security)
const isHttpOnly = cookieStr.toLowerCase().includes('httponly')
// * Determine sameSite (default lax)
const sameSiteMatch = cookieStr.match(/samesite=(\w+)/i)
const sameSite = (sameSiteMatch?.[1]?.toLowerCase() as 'strict' | 'lax' | 'none') || 'lax'
// * Extract max-age if present
const maxAgeMatch = cookieStr.match(/max-age=(\d+)/i)
const maxAge = maxAgeMatch ? parseInt(maxAgeMatch[1], 10) : 60 * 60 * 24 * 30
cookieStore.set(name.trim(), decodeURIComponent(value.trim()), {
httpOnly: isHttpOnly,
secure: process.env.NODE_ENV === 'production',
sameSite: sameSite,
path: '/',
domain: cookieDomain,
maxAge: maxAge
})
}
}
}
// * Also check for CSRF token in response header (fallback)
const csrfToken = res.headers.get('X-CSRF-Token')
if (csrfToken && !cookieStore.get('csrf_token')) {
cookieStore.set('csrf_token', csrfToken, {
httpOnly: false, // * Must be readable by JS for CSRF protection
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
domain: cookieDomain,
maxAge: 60 * 60 * 24 * 30
})
}
return {
success: true,
user: {

View File

@@ -37,6 +37,9 @@ export async function POST() {
const data = await res.json()
// * Get CSRF token from Auth API response header (for cookie rotation)
const csrfToken = res.headers.get('X-CSRF-Token')
cookieStore.set('access_token', data.access_token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
@@ -55,6 +58,18 @@ export async function POST() {
maxAge: 60 * 60 * 24 * 30
})
// * Set/update CSRF token cookie (non-httpOnly, for JS access)
if (csrfToken) {
cookieStore.set('csrf_token', csrfToken, {
httpOnly: false, // * Must be readable by JS for CSRF protection
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
domain: cookieDomain,
maxAge: 60 * 60 * 24 * 30
})
}
return NextResponse.json({ success: true, access_token: data.access_token })
} catch (error) {
return NextResponse.json({ error: 'Internal error' }, { status: 500 })

View File

@@ -2,7 +2,7 @@
import { OfflineBanner } from '@/components/OfflineBanner'
import { Footer } from '@/components/Footer'
import { Header } from '@ciphera-net/ui'
import { Header, type CipheraApp } from '@ciphera-net/ui'
import NotificationCenter from '@/components/notifications/NotificationCenter'
import { useAuth } from '@/lib/auth/context'
import { useOnlineStatus } from '@/lib/hooks/useOnlineStatus'
@@ -16,6 +16,34 @@ import { useRouter } from 'next/navigation'
const ORG_SWITCH_KEY = 'pulse_switching_org'
// * Available Ciphera apps for the app switcher
const CIPHERA_APPS: CipheraApp[] = [
{
id: 'pulse',
name: 'Pulse',
description: 'Your current app — Privacy-first analytics',
icon: 'https://ciphera.net/pulse_icon_no_margins.png',
href: 'https://pulse.ciphera.net',
isAvailable: false, // * Current app
},
{
id: 'drop',
name: 'Drop',
description: 'Secure file sharing',
icon: 'https://ciphera.net/drop_icon_no_margins.png',
href: 'https://drop.ciphera.net',
isAvailable: true,
},
{
id: 'auth',
name: 'Auth',
description: 'Your Ciphera account settings',
icon: 'https://ciphera.net/auth_icon_no_margins.png',
href: 'https://auth.ciphera.net',
isAvailable: true,
},
]
export default function LayoutContent({ children }: { children: React.ReactNode }) {
const auth = useAuth()
const router = useRouter()
@@ -87,6 +115,8 @@ export default function LayoutContent({ children }: { children: React.ReactNode
showPricing={true}
topOffset={showOfflineBar ? `${barHeightRem}rem` : undefined}
rightSideActions={auth.user ? <NotificationCenter /> : null}
apps={CIPHERA_APPS}
currentAppId="pulse"
customNavItems={
<>
{!auth.user && (

View File

@@ -2,7 +2,7 @@
import { useAuth } from '@/lib/auth/context'
import { logger } from '@/lib/utils/logger'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useState, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { motion } from 'framer-motion'
import { getSite, type Site } from '@/lib/api/sites'
@@ -148,6 +148,23 @@ export default function SiteDashboardPage() {
return { start: prevStart.toISOString().split('T')[0], end: prevEnd.toISOString().split('T')[0] }
}, [])
// * Visibility-aware polling intervals
// * Historical data: 60s when visible, paused when hidden
// * Real-time data: 5s when visible, 30s when hidden
const [isVisible, setIsVisible] = useState(true)
const dashboardIntervalRef = useRef<NodeJS.Timeout | null>(null)
const realtimeIntervalRef = useRef<NodeJS.Timeout | null>(null)
// * Track visibility state
useEffect(() => {
const handleVisibilityChange = () => {
const visible = document.visibilityState === 'visible'
setIsVisible(visible)
}
document.addEventListener('visibilitychange', handleVisibilityChange)
return () => document.removeEventListener('visibilitychange', handleVisibilityChange)
}, [])
const loadData = useCallback(async (silent = false) => {
try {
if (!silent) setLoading(true)
@@ -204,18 +221,60 @@ export default function SiteDashboardPage() {
const data = await getRealtime(siteId)
setRealtime(data.visitors)
} catch (error) {
// Silently fail for realtime updates
// * Silently fail for realtime updates
}
}, [siteId])
// * Visibility-aware polling for dashboard data (historical)
// * Refreshes every 60 seconds when tab is visible, pauses when hidden
useEffect(() => {
if (isSettingsLoaded) loadData()
const interval = setInterval(() => {
loadData(true)
if (!isSettingsLoaded) return
// * Initial load
loadData()
// * Clear existing interval
if (dashboardIntervalRef.current) {
clearInterval(dashboardIntervalRef.current)
}
// * Only poll when visible (saves server resources when tab is backgrounded)
if (isVisible) {
dashboardIntervalRef.current = setInterval(() => {
loadData(true)
}, 60000) // * 60 seconds for historical data
}
return () => {
if (dashboardIntervalRef.current) {
clearInterval(dashboardIntervalRef.current)
}
}
}, [siteId, dateRange, todayInterval, multiDayInterval, isSettingsLoaded, loadData, isVisible])
// * Visibility-aware polling for realtime data
// * Refreshes every 5 seconds when visible, every 30 seconds when hidden
useEffect(() => {
if (!isSettingsLoaded) return
// * Clear existing interval
if (realtimeIntervalRef.current) {
clearInterval(realtimeIntervalRef.current)
}
// * Different intervals based on visibility
const interval = isVisible ? 5000 : 30000 // * 5s visible, 30s hidden
realtimeIntervalRef.current = setInterval(() => {
loadRealtime()
}, 30000)
return () => clearInterval(interval)
}, [siteId, dateRange, todayInterval, multiDayInterval, isSettingsLoaded, loadData, loadRealtime])
}, interval)
return () => {
if (realtimeIntervalRef.current) {
clearInterval(realtimeIntervalRef.current)
}
}
}, [siteId, isSettingsLoaded, loadRealtime, isVisible])
useEffect(() => {
if (site?.domain) document.title = `${site.domain} | Pulse`

View File

@@ -22,6 +22,36 @@ export function getSignupUrl(redirectPath = '/auth/callback') {
return `${AUTH_URL}/signup?client_id=pulse-app&redirect_uri=${redirectUri}&response_type=code`
}
// * ============================================================================
// * CSRF Token Handling
// * ============================================================================
/**
* Get CSRF token from the csrf_token cookie (non-httpOnly)
* This is needed for state-changing requests to the Auth API
*/
function getCSRFToken(): string | null {
if (typeof document === 'undefined') return null
const cookies = document.cookie.split(';')
for (const cookie of cookies) {
const [name, value] = cookie.trim().split('=')
if (name === 'csrf_token') {
return decodeURIComponent(value)
}
}
return null
}
/**
* Check if a request method requires CSRF protection
* State-changing methods (POST, PUT, DELETE, PATCH) need CSRF tokens
*/
function isStateChangingMethod(method: string): boolean {
const stateChangingMethods = ['POST', 'PUT', 'DELETE', 'PATCH']
return stateChangingMethods.includes(method.toUpperCase())
}
export class ApiError extends Error {
status: number
data?: Record<string, unknown>
@@ -58,50 +88,144 @@ function onRefreshFailed(err: unknown) {
refreshSubscribers = []
}
// * ============================================================================
// * Request Deduplication & Caching
// * ============================================================================
/** Cache TTL in milliseconds (2 seconds) */
const CACHE_TTL_MS = 2_000
/** Stores in-flight requests for deduplication */
interface PendingRequest {
promise: Promise<unknown>
timestamp: number
}
const pendingRequests = new Map<string, PendingRequest>()
/** Stores cached responses */
interface CachedResponse {
data: unknown
timestamp: number
}
const responseCache = new Map<string, CachedResponse>()
/**
* Base API client with error handling
* Generate a unique key for a request based on endpoint and options
*/
function getRequestKey(endpoint: string, options: RequestInit): string {
const method = options.method || 'GET'
const body = options.body || ''
return `${method}:${endpoint}:${body}`
}
/**
* Clean up expired entries from pending requests and response cache
*/
function cleanupExpiredEntries(): void {
const now = Date.now()
// * Clean up stale pending requests (older than 30 seconds)
for (const [key, pending] of pendingRequests.entries()) {
if (now - pending.timestamp > 30_000) {
pendingRequests.delete(key)
}
}
// * Clean up stale cached responses (older than CACHE_TTL_MS)
for (const [key, cached] of responseCache.entries()) {
if (now - cached.timestamp > CACHE_TTL_MS) {
responseCache.delete(key)
}
}
}
/**
* Base API client with error handling, request deduplication, and short-term caching
*/
async function apiRequest<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
// * Skip deduplication for non-GET requests (mutations should always execute)
const method = options.method || 'GET'
const shouldDedupe = method === 'GET'
if (shouldDedupe) {
// * Clean up expired entries periodically
if (pendingRequests.size > 100 || responseCache.size > 100) {
cleanupExpiredEntries()
}
const requestKey = getRequestKey(endpoint, options)
// * Check if we have a recent cached response (within 2 seconds)
const cached = responseCache.get(requestKey)
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached.data as T
}
// * Check if there's an identical request in flight
const pending = pendingRequests.get(requestKey)
if (pending && Date.now() - pending.timestamp < 30000) {
return pending.promise as Promise<T>
}
}
// * Determine base URL
const isAuthRequest = endpoint.startsWith('/auth')
const baseUrl = isAuthRequest ? AUTH_API_URL : API_URL
// * Handle legacy endpoints that already include /api/ prefix
const url = endpoint.startsWith('/api/')
const url = endpoint.startsWith('/api/')
? `${baseUrl}${endpoint}`
: `${baseUrl}/api/v1${endpoint}`
const headers: HeadersInit = {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...options.headers,
}
// * Merge any additional headers from options
if (options.headers) {
const additionalHeaders = options.headers as Record<string, string>
Object.entries(additionalHeaders).forEach(([key, value]) => {
headers[key] = value
})
}
// * We rely on HttpOnly cookies, so no manual Authorization header injection.
// * We MUST set credentials: 'include' for the browser to send cookies cross-origin (or same-site).
// * Add CSRF token for state-changing requests to Auth API
// * Auth API uses Double Submit Cookie pattern for CSRF protection
if (isAuthRequest && isStateChangingMethod(method)) {
const csrfToken = getCSRFToken()
if (csrfToken) {
headers['X-CSRF-Token'] = csrfToken
}
}
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
const signal = options.signal ?? controller.signal
let response: Response
try {
response = await fetch(url, {
...options,
headers,
credentials: 'include', // * IMPORTANT: Send cookies
signal,
})
clearTimeout(timeoutId)
} catch (e) {
clearTimeout(timeoutId)
if (e instanceof Error && (e.name === 'AbortError' || e.name === 'TypeError')) {
throw new ApiError(AUTH_ERROR_MESSAGES.NETWORK, 0)
// * Create the request promise
const requestPromise = (async (): Promise<T> => {
let response: Response
try {
response = await fetch(url, {
...options,
headers,
credentials: 'include', // * IMPORTANT: Send cookies
signal,
})
clearTimeout(timeoutId)
} catch (e) {
clearTimeout(timeoutId)
if (e instanceof Error && (e.name === 'AbortError' || e.name === 'TypeError')) {
throw new ApiError(AUTH_ERROR_MESSAGES.NETWORK, 0)
}
throw e
}
throw e
}
if (!response.ok) {
if (response.status === 401) {
@@ -182,6 +306,38 @@ async function apiRequest<T>(
}
return response.json()
})()
// * For GET requests, track the promise for deduplication and cache the result
if (shouldDedupe) {
const requestKey = getRequestKey(endpoint, options)
// * Store in pending requests
pendingRequests.set(requestKey, {
promise: requestPromise as Promise<unknown>,
timestamp: Date.now(),
})
// * Clean up pending request and cache the result when done
requestPromise
.then((data) => {
// * Cache successful response
responseCache.set(requestKey, {
data,
timestamp: Date.now(),
})
// * Remove from pending
pendingRequests.delete(requestKey)
return data
})
.catch((error) => {
// * Remove from pending on error too
pendingRequests.delete(requestKey)
throw error
})
}
return requestPromise
}
export const authFetch = apiRequest

View File

@@ -332,11 +332,11 @@ export async function getDashboard(siteId: string, startDate?: string, endDate?:
}
export async function getPublicDashboard(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
interval?: string,
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
interval?: string,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardData> {
@@ -344,9 +344,256 @@ export async function getPublicDashboard(
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
if (interval) params.append('interval', interval)
appendAuthParams(params, { password, captcha })
params.append('limit', limit.toString())
return apiRequest<DashboardData>(`/public/sites/${siteId}/dashboard?${params.toString()}`)
}
// * ============================================================================
// * Focused Dashboard Endpoints (Fix 4.2: Efficient Data Transfer)
// * These split the massive dashboard payload into smaller, focused chunks
// * ============================================================================
export interface DashboardOverviewData {
site: Site
stats: Stats
realtime_visitors: number
daily_stats: DailyStat[]
}
export async function getDashboardOverview(
siteId: string,
startDate?: string,
endDate?: string,
interval?: string
): Promise<DashboardOverviewData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
if (interval) params.append('interval', interval)
return apiRequest<DashboardOverviewData>(`/sites/${siteId}/dashboard/overview?${params.toString()}`)
}
export async function getPublicDashboardOverview(
siteId: string,
startDate?: string,
endDate?: string,
interval?: string,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardOverviewData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
if (interval) params.append('interval', interval)
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardOverviewData>(`/public/sites/${siteId}/dashboard/overview?${params.toString()}`)
}
export interface DashboardPagesData {
top_pages: TopPage[]
entry_pages: TopPage[]
exit_pages: TopPage[]
}
export async function getDashboardPages(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10
): Promise<DashboardPagesData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
return apiRequest<DashboardPagesData>(`/sites/${siteId}/dashboard/pages?${params.toString()}`)
}
export async function getPublicDashboardPages(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardPagesData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardPagesData>(`/public/sites/${siteId}/dashboard/pages?${params.toString()}`)
}
export interface DashboardLocationsData {
countries: CountryStat[]
cities: CityStat[]
regions: RegionStat[]
}
export async function getDashboardLocations(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
countryLimit = 250
): Promise<DashboardLocationsData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
params.append('country_limit', countryLimit.toString())
return apiRequest<DashboardLocationsData>(`/sites/${siteId}/dashboard/locations?${params.toString()}`)
}
export async function getPublicDashboardLocations(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
countryLimit = 250,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardLocationsData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
params.append('country_limit', countryLimit.toString())
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardLocationsData>(`/public/sites/${siteId}/dashboard/locations?${params.toString()}`)
}
export interface DashboardDevicesData {
browsers: BrowserStat[]
os: OSStat[]
devices: DeviceStat[]
screen_resolutions: ScreenResolutionStat[]
}
export async function getDashboardDevices(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10
): Promise<DashboardDevicesData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
return apiRequest<DashboardDevicesData>(`/sites/${siteId}/dashboard/devices?${params.toString()}`)
}
export async function getPublicDashboardDevices(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardDevicesData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardDevicesData>(`/public/sites/${siteId}/dashboard/devices?${params.toString()}`)
}
export interface DashboardReferrersData {
top_referrers: TopReferrer[]
}
export async function getDashboardReferrers(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10
): Promise<DashboardReferrersData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
return apiRequest<DashboardReferrersData>(`/sites/${siteId}/dashboard/referrers?${params.toString()}`)
}
export async function getPublicDashboardReferrers(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardReferrersData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardReferrersData>(`/public/sites/${siteId}/dashboard/referrers?${params.toString()}`)
}
export interface DashboardPerformanceData {
performance?: PerformanceStats
performance_by_page?: PerformanceByPageStat[]
}
export async function getDashboardPerformance(
siteId: string,
startDate?: string,
endDate?: string
): Promise<DashboardPerformanceData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
return apiRequest<DashboardPerformanceData>(`/sites/${siteId}/dashboard/performance?${params.toString()}`)
}
export async function getPublicDashboardPerformance(
siteId: string,
startDate?: string,
endDate?: string,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardPerformanceData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardPerformanceData>(`/public/sites/${siteId}/dashboard/performance?${params.toString()}`)
}
export interface DashboardGoalsData {
goal_counts: GoalCountStat[]
}
export async function getDashboardGoals(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10
): Promise<DashboardGoalsData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
return apiRequest<DashboardGoalsData>(`/sites/${siteId}/dashboard/goals?${params.toString()}`)
}
export async function getPublicDashboardGoals(
siteId: string,
startDate?: string,
endDate?: string,
limit = 10,
password?: string,
captcha?: { captcha_id?: string, captcha_solution?: string, captcha_token?: string }
): Promise<DashboardGoalsData> {
const params = new URLSearchParams()
if (startDate) params.append('start_date', startDate)
if (endDate) params.append('end_date', endDate)
params.append('limit', limit.toString())
appendAuthParams(params, { password, captcha })
return apiRequest<DashboardGoalsData>(`/public/sites/${siteId}/dashboard/goals?${params.toString()}`)
}

View File

@@ -0,0 +1,128 @@
// * Custom hook for visibility-aware polling
// * Pauses polling when tab is not visible, resumes when visible
// * Reduces server load when users aren't actively viewing the dashboard
import { useEffect, useRef, useState, useCallback } from 'react'
interface UseVisibilityPollingOptions {
// * Polling interval when tab is visible (in milliseconds)
visibleInterval: number
// * Polling interval when tab is hidden (in milliseconds, or null to pause)
hiddenInterval: number | null
}
interface UseVisibilityPollingReturn {
// * Whether polling is currently active
isPolling: boolean
// * Time since last poll
lastPollTime: number | null
// * Force a poll immediately
triggerPoll: () => void
}
export function useVisibilityPolling(
callback: () => void | Promise<void>,
options: UseVisibilityPollingOptions
): UseVisibilityPollingReturn {
const { visibleInterval, hiddenInterval } = options
const [isPolling, setIsPolling] = useState(false)
const [lastPollTime, setLastPollTime] = useState<number | null>(null)
const intervalRef = useRef<NodeJS.Timeout | null>(null)
const callbackRef = useRef(callback)
// * Keep callback reference up to date
useEffect(() => {
callbackRef.current = callback
}, [callback])
// * Get current polling interval based on visibility
const getInterval = useCallback((): number | null => {
if (typeof document === 'undefined') return null
const isVisible = document.visibilityState === 'visible'
if (isVisible) {
return visibleInterval
}
return hiddenInterval
}, [visibleInterval, hiddenInterval])
// * Start polling with current interval
const startPolling = useCallback(() => {
const interval = getInterval()
if (interval === null) {
setIsPolling(false)
return
}
setIsPolling(true)
// * Clear any existing interval
if (intervalRef.current) {
clearInterval(intervalRef.current)
}
// * Set up new interval
intervalRef.current = setInterval(() => {
callbackRef.current()
setLastPollTime(Date.now())
}, interval)
}, [getInterval])
// * Stop polling
const stopPolling = useCallback(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current)
intervalRef.current = null
}
setIsPolling(false)
}, [])
// * Trigger immediate poll
const triggerPoll = useCallback(() => {
callbackRef.current()
setLastPollTime(Date.now())
// * Restart polling timer
startPolling()
}, [startPolling])
// * Handle visibility changes
useEffect(() => {
if (typeof document === 'undefined') return
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
// * Tab became visible - resume polling with visible interval
startPolling()
// * Trigger immediate poll to get fresh data
triggerPoll()
} else {
// * Tab hidden - switch to hidden interval or pause
const interval = getInterval()
if (interval === null) {
stopPolling()
} else {
// * Restart with hidden interval
startPolling()
}
}
}
// * Listen for visibility changes
document.addEventListener('visibilitychange', handleVisibilityChange)
// * Start polling initially
startPolling()
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange)
stopPolling()
}
}, [startPolling, stopPolling, triggerPoll, getInterval])
return {
isPolling,
lastPollTime,
triggerPoll,
}
}

234
lib/swr/dashboard.ts Normal file
View File

@@ -0,0 +1,234 @@
// * SWR configuration for dashboard data fetching
// * Implements stale-while-revalidate pattern for efficient data updates
import useSWR from 'swr'
import {
getDashboard,
getDashboardOverview,
getDashboardPages,
getDashboardLocations,
getDashboardDevices,
getDashboardReferrers,
getDashboardPerformance,
getDashboardGoals,
getRealtime,
getStats,
getDailyStats,
} from '@/lib/api/stats'
import { getSite } from '@/lib/api/sites'
import type { Site } from '@/lib/api/sites'
import type {
Stats,
DailyStat,
DashboardOverviewData,
DashboardPagesData,
DashboardLocationsData,
DashboardDevicesData,
DashboardReferrersData,
DashboardPerformanceData,
DashboardGoalsData,
} from '@/lib/api/stats'
// * SWR fetcher functions
const fetchers = {
site: (siteId: string) => getSite(siteId),
dashboard: (siteId: string, start: string, end: string) => getDashboard(siteId, start, end),
dashboardOverview: (siteId: string, start: string, end: string) => getDashboardOverview(siteId, start, end),
dashboardPages: (siteId: string, start: string, end: string) => getDashboardPages(siteId, start, end),
dashboardLocations: (siteId: string, start: string, end: string) => getDashboardLocations(siteId, start, end),
dashboardDevices: (siteId: string, start: string, end: string) => getDashboardDevices(siteId, start, end),
dashboardReferrers: (siteId: string, start: string, end: string) => getDashboardReferrers(siteId, start, end),
dashboardPerformance: (siteId: string, start: string, end: string) => getDashboardPerformance(siteId, start, end),
dashboardGoals: (siteId: string, start: string, end: string) => getDashboardGoals(siteId, start, end),
stats: (siteId: string, start: string, end: string) => getStats(siteId, start, end),
dailyStats: (siteId: string, start: string, end: string, interval: 'hour' | 'day' | 'minute') =>
getDailyStats(siteId, start, end, interval),
realtime: (siteId: string) => getRealtime(siteId),
}
// * Standard SWR config for dashboard data
const dashboardSWRConfig = {
// * Keep stale data visible while revalidating (better UX)
revalidateOnFocus: false,
// * Revalidate when reconnecting (fresh data after offline)
revalidateOnReconnect: true,
// * Retry failed requests
shouldRetryOnError: true,
errorRetryCount: 3,
// * Error retry interval with exponential backoff
errorRetryInterval: 5000,
}
// * Hook for site data (loads once, refreshes rarely)
export function useSite(siteId: string) {
return useSWR<Site>(
siteId ? ['site', siteId] : null,
() => fetchers.site(siteId),
{
...dashboardSWRConfig,
// * Site data changes rarely, refresh every 5 minutes
refreshInterval: 5 * 60 * 1000,
// * Deduping interval to prevent duplicate requests
dedupingInterval: 30 * 1000,
}
)
}
// * Hook for dashboard summary data (refreshed less frequently)
export function useDashboard(siteId: string, start: string, end: string) {
return useSWR(
siteId && start && end ? ['dashboard', siteId, start, end] : null,
() => fetchers.dashboard(siteId, start, end),
{
...dashboardSWRConfig,
// * Refresh every 60 seconds for dashboard summary
refreshInterval: 60 * 1000,
// * Deduping interval to prevent duplicate requests
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for stats (refreshed less frequently)
export function useStats(siteId: string, start: string, end: string) {
return useSWR<Stats>(
siteId && start && end ? ['stats', siteId, start, end] : null,
() => fetchers.stats(siteId, start, end),
{
...dashboardSWRConfig,
// * Refresh every 60 seconds for stats
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for daily stats (refreshed less frequently)
export function useDailyStats(
siteId: string,
start: string,
end: string,
interval: 'hour' | 'day' | 'minute'
) {
return useSWR<DailyStat[]>(
siteId && start && end ? ['dailyStats', siteId, start, end, interval] : null,
() => fetchers.dailyStats(siteId, start, end, interval),
{
...dashboardSWRConfig,
// * Refresh every 60 seconds for chart data
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for realtime visitor count (refreshed frequently)
export function useRealtime(siteId: string, refreshInterval: number = 5000) {
return useSWR<{ visitors: number }>(
siteId ? ['realtime', siteId] : null,
() => fetchers.realtime(siteId),
{
...dashboardSWRConfig,
// * Refresh frequently for real-time data (default 5 seconds)
refreshInterval,
// * Short deduping for real-time
dedupingInterval: 2000,
// * Keep previous data while loading new data
keepPreviousData: true,
}
)
}
// * Hook for focused dashboard overview data (Fix 4.2: Efficient Data Transfer)
export function useDashboardOverview(siteId: string, start: string, end: string) {
return useSWR<DashboardOverviewData>(
siteId && start && end ? ['dashboardOverview', siteId, start, end] : null,
() => fetchers.dashboardOverview(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard pages data
export function useDashboardPages(siteId: string, start: string, end: string) {
return useSWR<DashboardPagesData>(
siteId && start && end ? ['dashboardPages', siteId, start, end] : null,
() => fetchers.dashboardPages(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard locations data
export function useDashboardLocations(siteId: string, start: string, end: string) {
return useSWR<DashboardLocationsData>(
siteId && start && end ? ['dashboardLocations', siteId, start, end] : null,
() => fetchers.dashboardLocations(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard devices data
export function useDashboardDevices(siteId: string, start: string, end: string) {
return useSWR<DashboardDevicesData>(
siteId && start && end ? ['dashboardDevices', siteId, start, end] : null,
() => fetchers.dashboardDevices(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard referrers data
export function useDashboardReferrers(siteId: string, start: string, end: string) {
return useSWR<DashboardReferrersData>(
siteId && start && end ? ['dashboardReferrers', siteId, start, end] : null,
() => fetchers.dashboardReferrers(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard performance data
export function useDashboardPerformance(siteId: string, start: string, end: string) {
return useSWR<DashboardPerformanceData>(
siteId && start && end ? ['dashboardPerformance', siteId, start, end] : null,
() => fetchers.dashboardPerformance(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Hook for focused dashboard goals data
export function useDashboardGoals(siteId: string, start: string, end: string) {
return useSWR<DashboardGoalsData>(
siteId && start && end ? ['dashboardGoals', siteId, start, end] : null,
() => fetchers.dashboardGoals(siteId, start, end),
{
...dashboardSWRConfig,
refreshInterval: 60 * 1000,
dedupingInterval: 10 * 1000,
}
)
}
// * Re-export for convenience
export { fetchers }

31
package-lock.json generated
View File

@@ -8,7 +8,7 @@
"name": "pulse-frontend",
"version": "0.11.1-alpha",
"dependencies": {
"@ciphera-net/ui": "^0.0.64",
"@ciphera-net/ui": "^0.0.69",
"@ducanh2912/next-pwa": "^10.2.9",
"@radix-ui/react-icons": "^1.3.0",
"@simplewebauthn/browser": "^13.2.2",
@@ -31,6 +31,7 @@
"react-simple-maps": "^3.0.0",
"recharts": "^2.15.0",
"sonner": "^2.0.7",
"swr": "^2.3.3",
"xlsx": "^0.18.5"
},
"devDependencies": {
@@ -1542,9 +1543,9 @@
}
},
"node_modules/@ciphera-net/ui": {
"version": "0.0.64",
"resolved": "https://npm.pkg.github.com/download/@ciphera-net/ui/0.0.64/1630605518a705ba9e74f003b9c66646bcc699ac",
"integrity": "sha512-xY+yALuCqWtsH78t6xmy2JQnQ8WFSlihElHnetFr6GQp9mOTCA5rlQq+a8hyg4xW7uXtIbKmPBxVnH5TlH9lBQ==",
"version": "0.0.69",
"resolved": "https://npm.pkg.github.com/download/@ciphera-net/ui/0.0.69/f4bdafba179e509c05209a984770b262bb1a8331",
"integrity": "sha512-ERx6Qs4A+igzNSN5FwkLqZlsnorh9wM9P9SrdyAeMAlf9Dxvwwjvu1vWM6NApEL4oVfRdSHswhdtrcK/PQIy0g==",
"dependencies": {
"@radix-ui/react-icons": "^1.3.0",
"clsx": "^2.1.0",
@@ -10356,6 +10357,19 @@
"node": ">=12.0.0"
}
},
"node_modules/swr": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/swr/-/swr-2.4.0.tgz",
"integrity": "sha512-sUlC20T8EOt1pHmDiqueUWMmRRX03W7w5YxovWX7VR2KHEPCTMly85x05vpkP5i6Bu4h44ePSMD9Tc+G2MItFw==",
"license": "MIT",
"dependencies": {
"dequal": "^2.0.3",
"use-sync-external-store": "^1.6.0"
},
"peerDependencies": {
"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/tailwind-merge": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz",
@@ -11113,6 +11127,15 @@
"punycode": "^2.1.0"
}
},
"node_modules/use-sync-external-store": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@@ -10,7 +10,7 @@
"type-check": "tsc --noEmit"
},
"dependencies": {
"@ciphera-net/ui": "^0.0.64",
"@ciphera-net/ui": "^0.0.69",
"@ducanh2912/next-pwa": "^10.2.9",
"@radix-ui/react-icons": "^1.3.0",
"@simplewebauthn/browser": "^13.2.2",
@@ -33,6 +33,7 @@
"react-simple-maps": "^3.0.0",
"recharts": "^2.15.0",
"sonner": "^2.0.7",
"swr": "^2.3.3",
"xlsx": "^0.18.5"
},
"overrides": {