Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

refactor(uptime): remove uptime monitoring components and API (#1114)

Goldflag0ae173193633
diff --git a/PRODUCT.md b/PRODUCT.md
index fc52d61e8..fce7710d2 100644
--- a/PRODUCT.md
+++ b/PRODUCT.md
@@ -18,7 +18,7 @@ Shared context: they open Rybbit to answer a specific question (what's trending,
## Product Purpose
-Rybbit is an open-source, privacy-friendly, cookieless web and product analytics platform: the modern alternative to Google Analytics. It covers the full analytics surface (sessions, users, pageviews, bounce rate, funnels, journeys, retention, goals, custom events, session replay, error tracking, uptime, and 3-level location maps) while staying fast to set up and intuitive to read.
+Rybbit is an open-source, privacy-friendly, cookieless web and product analytics platform: the modern alternative to Google Analytics. It covers the full analytics surface (sessions, users, pageviews, bounce rate, funnels, journeys, retention, goals, custom events, session replay, error tracking, and 3-level location maps) while staying fast to set up and intuitive to read.
Success looks like: a user installs the script in minutes, lands on a dashboard that's immediately legible, and trusts the numbers. Depth is available (advanced filters across 15+ dimensions, custom SQL queries, replays) but never blocks the first answer. Privacy is a feature, not a compromise.
diff --git a/client/AGENTS.md b/client/AGENTS.md
index c4ebfa130..f9c30ba4a 100644
--- a/client/AGENTS.md
+++ b/client/AGENTS.md
@@ -33,7 +33,6 @@ Run commands from `client/`.
- `src/app/[site]/` - per-site analytics dashboard routes.
- `src/app/admin/` - admin UI.
- `src/app/settings/` - account, organization, billing, and team settings.
-- `src/app/uptime/` - uptime monitoring UI.
- `src/api/` - endpoint functions and React Query hooks.
- `src/components/ui/` - Shadcn UI primitives.
- `src/components/` - shared feature components.
diff --git a/client/CLAUDE.md b/client/CLAUDE.md
index 6d396eb9e..d1ebac232 100644
--- a/client/CLAUDE.md
+++ b/client/CLAUDE.md
@@ -32,7 +32,6 @@ src/
β”‚ β”œβ”€β”€ analytics/ # Analytics endpoints + React Query hooks
β”‚ β”œβ”€β”€ admin/ # Admin endpoints + hooks
β”‚ β”œβ”€β”€ gsc/ # Google Search Console
-β”‚ β”œβ”€β”€ uptime/ # Uptime monitoring
β”‚ β”œβ”€β”€ types.ts # Shared types (CommonApiParams, Filter, etc.)
β”‚ └── utils.ts # authedFetch, buildApiParams
β”œβ”€β”€ app/ # Next.js App Router pages
@@ -40,7 +39,6 @@ src/
β”‚ β”œβ”€β”€ admin/ # Admin panel
β”‚ β”œβ”€β”€ auth/ # Auth flows
β”‚ β”œβ”€β”€ settings/ # User settings
-β”‚ β”œβ”€β”€ uptime/ # Uptime dashboard
β”‚ β”œβ”€β”€ layout.tsx # Root layout
β”‚ └── Providers.tsx # Provider stack
β”œβ”€β”€ components/
@@ -122,7 +120,6 @@ Only `timezone` is persisted; everything else is session-only.
- `/admin` – admin panel
- `/login`, `/signup` – auth pages
- `/settings` – user settings
-- `/uptime` – uptime monitoring
Middleware in `proxy.ts` handles redirects and OAuth callbacks (`/auth/callback/github`, `/auth/callback/google`).
diff --git a/client/src/api/CLAUDE.md b/client/src/api/CLAUDE.md
index 172778b9b..95a8a4c41 100644
--- a/client/src/api/CLAUDE.md
+++ b/client/src/api/CLAUDE.md
@@ -14,7 +14,6 @@ api/
β”‚ └── hooks/ # React Query hooks
β”œβ”€β”€ gsc/ # Google Search Console integration
β”œβ”€β”€ stripe/ # Stripe billing integration
-β”œβ”€β”€ uptime/ # Uptime monitoring
β”œβ”€β”€ types.ts # Shared API types (APIResponse)
└── utils.ts # Shared utilities (authedFetch, buildApiParams)
```
diff --git a/client/src/api/uptime/incidents.ts b/client/src/api/uptime/incidents.ts
deleted file mode 100644
index 8bd3c8080..000000000
--- a/client/src/api/uptime/incidents.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-
-export interface UptimeIncident {
- id: number;
- organizationId: string;
- monitorId: number;
- monitorName: string;
- region?: string;
- affectedRegions?: string[];
- startTime: string;
- endTime?: string;
- status: "active" | "acknowledged" | "resolved";
- acknowledgedBy?: string;
- acknowledgedAt?: string;
- resolvedBy?: string;
- resolvedAt?: string;
- lastError?: string;
- lastErrorType?: string;
- failureCount: number;
- createdAt: string;
- updatedAt: string;
-}
-
-interface GetIncidentsParams {
- status?: "active" | "acknowledged" | "resolved" | "all";
- limit?: number;
- offset?: number;
-}
-
-async function getIncidents(params?: GetIncidentsParams) {
- const queryParams = new URLSearchParams();
- if (params?.status) queryParams.append("status", params.status);
- if (params?.limit) queryParams.append("limit", params.limit.toString());
- if (params?.offset) queryParams.append("offset", params.offset.toString());
-
- const queryString = queryParams.toString();
- const url = queryString ? `/uptime/incidents?${queryString}` : "/uptime/incidents";
-
- return authedFetch<{
- incidents: UptimeIncident[];
- pagination: {
- total: number;
- limit: number;
- offset: number;
- };
- }>(url);
-}
-
-async function acknowledgeIncident(incidentId: number) {
- return authedFetch(`/uptime/incidents/${incidentId}/acknowledge`, undefined, { method: "PATCH", data: {} });
-}
-
-async function resolveIncident(incidentId: number) {
- return authedFetch(`/uptime/incidents/${incidentId}/resolve`, undefined, { method: "PATCH", data: {} });
-}
-
-// Hooks
-export function useIncidents(params?: GetIncidentsParams) {
- return useQuery({
- queryKey: ["uptime-incidents", params],
- queryFn: () => getIncidents(params),
- });
-}
-
-export function useAcknowledgeIncident() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: acknowledgeIncident,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["uptime-incidents"] });
- },
- });
-}
-
-export function useResolveIncident() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: resolveIncident,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["uptime-incidents"] });
- },
- });
-}
diff --git a/client/src/api/uptime/monitors.ts b/client/src/api/uptime/monitors.ts
deleted file mode 100644
index c12f93d7f..000000000
--- a/client/src/api/uptime/monitors.ts
+++ /dev/null
@@ -1,423 +0,0 @@
-import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-import { timeZone } from "../../lib/dateTimeUtils";
-
-// Validation rule types
-export type ValidationRule =
- | {
- type: "status_code";
- operator: "equals" | "not_equals" | "in" | "not_in";
- value: number | number[];
- }
- | {
- type: "response_time";
- operator: "less_than" | "greater_than";
- value: number;
- }
- | {
- type: "response_body_contains" | "response_body_not_contains";
- value: string;
- caseSensitive?: boolean;
- }
- | {
- type: "header_exists";
- header: string;
- }
- | {
- type: "header_value";
- header: string;
- operator: "equals" | "contains";
- value: string;
- }
- | {
- type: "response_size";
- operator: "less_than" | "greater_than";
- value: number;
- };
-
-export interface UptimeMonitor {
- id: number;
- organizationId: string;
- name: string;
- monitorType: "http" | "tcp";
- intervalSeconds: number;
- enabled: boolean;
- httpConfig?: {
- url: string;
- method: string;
- headers?: Record<string, string>;
- body?: string;
- auth?: {
- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
- credentials?: {
- username?: string;
- password?: string;
- token?: string;
- headerName?: string;
- headerValue?: string;
- };
- };
- followRedirects?: boolean;
- timeoutMs?: number;
- ipVersion?: "any" | "ipv4" | "ipv6";
- userAgent?: string;
- };
- tcpConfig?: {
- host: string;
- port: number;
- timeoutMs?: number;
- };
- validationRules: ValidationRule[];
- monitoringType: "local" | "global";
- selectedRegions: string[];
- createdAt: string;
- updatedAt: string;
- createdBy: string;
- status?: {
- monitorId: number;
- lastCheckedAt?: string;
- currentStatus: "up" | "down" | "unknown";
- consecutiveFailures: number;
- consecutiveSuccesses: number;
- uptimePercentage24h?: number;
- uptimePercentage7d?: number;
- uptimePercentage30d?: number;
- updatedAt: string;
- };
-}
-
-export interface MonitorStats {
- hours: number;
- startTime: string;
- endTime: string;
- region?: string;
- bucket?: string;
- monitorType?: string;
- stats: {
- totalChecks: number;
- successfulChecks: number;
- failedChecks: number;
- timeoutChecks: number;
- uptimePercentage: number;
- responseTime: {
- avg: number;
- min: number;
- max: number;
- p50: number;
- p75: number;
- p90: number;
- p95: number;
- p99: number;
- };
- };
- distribution: Array<{
- hour: string;
- avg_response_time: number;
- avg_dns_time?: number;
- avg_tcp_time?: number;
- avg_tls_time?: number;
- avg_ttfb?: number;
- avg_transfer_time?: number;
- check_count: number;
- success_count: number;
- }>;
-}
-
-export interface MonitorUptime {
- monitorId: number;
- totalUptimeSeconds: number;
- currentUptimeSeconds: number;
- totalMonitoringSeconds: number;
- lastDowntime: {
- timestamp: string;
- error?: string;
- errorType?: string;
- status: string;
- } | null;
- monitoringSince: string | null;
- lastCheck: string | null;
- uptimePercentage: number;
- totalChecks: number;
- failedChecks: number;
-}
-
-export interface MonitorEvent {
- monitor_id: number;
- organization_id: string;
- timestamp: string;
- monitor_type: string;
- monitor_url: string;
- monitor_name: string;
- region: string;
- status: "success" | "failure" | "timeout";
- status_code?: number;
- response_time_ms: number;
- dns_time_ms?: number;
- tcp_time_ms?: number;
- tls_time_ms?: number;
- ttfb_ms?: number;
- transfer_time_ms?: number;
- validation_errors?: string[];
- response_headers?: Record<string, string>;
- response_size_bytes?: number;
- port?: number;
- error_message?: string;
- error_type?: string;
-}
-
-async function getMonitors(params?: {
- organizationId?: string;
- enabled?: boolean;
- monitorType?: "http" | "tcp";
- limit?: number;
- offset?: number;
-}) {
- const queryParams = new URLSearchParams();
- if (params?.organizationId) queryParams.append("organizationId", params.organizationId);
- if (params?.enabled !== undefined) queryParams.append("enabled", params.enabled.toString());
- if (params?.monitorType) queryParams.append("monitorType", params.monitorType);
- if (params?.limit) queryParams.append("limit", params.limit.toString());
- if (params?.offset) queryParams.append("offset", params.offset.toString());
-
- const queryString = queryParams.toString();
- const url = queryString ? `/uptime/monitors?${queryString}` : "/uptime/monitors";
-
- return authedFetch<UptimeMonitor[]>(url);
-}
-
-async function getMonitor(monitorId: number) {
- return authedFetch<UptimeMonitor>(`/uptime/monitors/${monitorId}`);
-}
-
-async function getMonitorStats(
- monitorId: number,
- params?: {
- startTime?: string;
- endTime?: string;
- region?: string;
- hours?: number;
- bucket?: "minute" | "five_minutes" | "ten_minutes" | "fifteen_minutes" | "hour" | "day" | "week" | "month" | "year";
- }
-) {
- const queryParams = new URLSearchParams();
-
- if (params?.region) queryParams.append("region", params.region);
- if (params?.hours) queryParams.append("hours", params.hours.toString());
- if (params?.bucket) queryParams.append("bucket", params.bucket);
-
- const queryString = queryParams.toString();
- const url = queryString
- ? `/uptime/monitors/${monitorId}/stats?${queryString}`
- : `/uptime/monitors/${monitorId}/stats`;
-
- return authedFetch<MonitorStats>(url);
-}
-
-async function getMonitorEvents(
- monitorId: number,
- params?: {
- status?: "success" | "failure" | "timeout";
- region?: string;
- limit?: number;
- offset?: number;
- }
-) {
- const queryParams = new URLSearchParams();
- if (params?.status) queryParams.append("status", params.status);
- if (params?.region) queryParams.append("region", params.region);
- if (params?.limit) queryParams.append("limit", params.limit.toString());
- if (params?.offset) queryParams.append("offset", params.offset.toString());
-
- const queryString = queryParams.toString();
- const url = queryString
- ? `/uptime/monitors/${monitorId}/events?${queryString}`
- : `/uptime/monitors/${monitorId}/events`;
-
- return authedFetch<{
- events: MonitorEvent[];
- pagination: {
- total: number;
- limit: number;
- offset: number;
- };
- }>(url);
-}
-
-async function getMonitorUptime(monitorId: number) {
- return authedFetch<MonitorUptime>(`/uptime/monitors/${monitorId}/uptime`);
-}
-
-async function getMonitorUptimeBuckets(
- monitorId: number,
- params?: {
- bucket?: "hour" | "day" | "week";
- days?: number;
- }
-) {
- const queryParams = new URLSearchParams();
- if (params?.bucket) queryParams.append("bucket", params.bucket);
- if (params?.days) queryParams.append("days", params.days.toString());
-
- queryParams.append("timeZone", timeZone);
-
- const queryString = queryParams.toString();
- const url = queryString
- ? `/uptime/monitors/${monitorId}/buckets?${queryString}`
- : `/uptime/monitors/${monitorId}/buckets`;
-
- return authedFetch<{
- buckets: Array<{
- bucket_time: string;
- bucket_formatted: string;
- total_checks: number;
- successful_checks: number;
- failed_checks: number;
- timeout_checks: number;
- uptime_percentage: number;
- }>;
- bucket: string;
- days: number;
- monitorId: number;
- }>(url);
-}
-
-// Hooks
-export function useMonitors(params?: Parameters<typeof getMonitors>[0]) {
- return useQuery({
- queryKey: ["uptime-monitors", params],
- queryFn: () => getMonitors(params),
- });
-}
-
-export function useMonitor(monitorId: number | undefined) {
- return useQuery({
- queryKey: ["uptime-monitor", monitorId],
- queryFn: () => (monitorId ? getMonitor(monitorId) : Promise.reject("No monitor ID")),
- enabled: !!monitorId,
- });
-}
-
-export function useMonitorStats(monitorId: number | undefined, params?: Parameters<typeof getMonitorStats>[1]) {
- return useQuery({
- queryKey: ["uptime-monitor-stats", monitorId, params],
- queryFn: () => (monitorId ? getMonitorStats(monitorId, params) : Promise.reject("No monitor ID")),
- enabled: !!monitorId,
- });
-}
-
-export function useMonitorEvents(monitorId: number | undefined, params?: Parameters<typeof getMonitorEvents>[1]) {
- return useQuery({
- queryKey: ["uptime-monitor-events", monitorId, params],
- queryFn: () => (monitorId ? getMonitorEvents(monitorId, params) : Promise.reject("No monitor ID")),
- enabled: !!monitorId,
- });
-}
-
-export function useMonitorEventsInfinite(
- monitorId: number | undefined,
- params?: Omit<Parameters<typeof getMonitorEvents>[1], "offset">
-) {
- return useInfiniteQuery({
- queryKey: ["uptime-monitor-events-infinite", monitorId, params],
- queryFn: ({ pageParam = 0 }) =>
- monitorId
- ? getMonitorEvents(monitorId, { ...params, offset: pageParam, limit: 100 })
- : Promise.reject("No monitor ID"),
- getNextPageParam: (lastPage, pages) => {
- const currentOffset = (pages.length - 1) * 100;
- const hasMore = currentOffset + lastPage.events.length < lastPage.pagination.total;
- return hasMore ? currentOffset + 100 : undefined;
- },
- enabled: !!monitorId,
- initialPageParam: 0,
- });
-}
-
-export function useMonitorUptime(monitorId: number | undefined) {
- return useQuery({
- queryKey: ["uptime-monitor-uptime", monitorId],
- queryFn: () => (monitorId ? getMonitorUptime(monitorId) : Promise.reject("No monitor ID")),
- enabled: !!monitorId,
- });
-}
-
-export function useMonitorUptimeBuckets(
- monitorId: number | undefined,
- params?: Parameters<typeof getMonitorUptimeBuckets>[1]
-) {
- return useQuery({
- queryKey: ["uptime-monitor-buckets", monitorId, params],
- queryFn: () => (monitorId ? getMonitorUptimeBuckets(monitorId, params) : Promise.reject("No monitor ID")),
- enabled: !!monitorId,
- });
-}
-
-// Mutations
-export interface CreateMonitorInput {
- organizationId: string;
- name: string;
- monitorType: "http" | "tcp";
- intervalSeconds: number;
- enabled?: boolean;
- httpConfig?: UptimeMonitor["httpConfig"];
- tcpConfig?: UptimeMonitor["tcpConfig"];
- validationRules?: ValidationRule[];
- regions?: string[];
-}
-
-export interface UpdateMonitorInput {
- name?: string;
- intervalSeconds?: number;
- enabled?: boolean;
- httpConfig?: UptimeMonitor["httpConfig"];
- tcpConfig?: UptimeMonitor["tcpConfig"];
- validationRules?: ValidationRule[];
- regions?: string[];
-}
-
-async function createMonitor(data: CreateMonitorInput) {
- return authedFetch(`/uptime/monitors`, undefined, { method: "POST", data });
-}
-
-async function updateMonitor(monitorId: number, data: UpdateMonitorInput) {
- return authedFetch(`/uptime/monitors/${monitorId}`, undefined, { method: "PUT", data });
-}
-
-async function deleteMonitor(monitorId: number) {
- return authedFetch(`/uptime/monitors/${monitorId}`, undefined, { method: "DELETE" });
-}
-
-export function useCreateMonitor() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: createMonitor,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
- },
- });
-}
-
-export function useUpdateMonitor() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: ({ monitorId, data }: { monitorId: number; data: UpdateMonitorInput }) =>
- updateMonitor(monitorId, data),
- onSuccess: (_, variables) => {
- queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
- queryClient.invalidateQueries({ queryKey: ["uptime-monitor", variables.monitorId] });
- },
- });
-}
-
-export function useDeleteMonitor() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: deleteMonitor,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["uptime-monitors"] });
- },
- });
-}
diff --git a/client/src/api/uptime/notifications.ts b/client/src/api/uptime/notifications.ts
deleted file mode 100644
index 7721af63b..000000000
--- a/client/src/api/uptime/notifications.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-
-export interface NotificationChannel {
- id: number;
- organizationId: string;
- type: "email" | "discord" | "slack" | "sms";
- name: string;
- enabled: boolean;
- config: {
- email?: string;
- webhookUrl?: string;
- slackWebhookUrl?: string;
- slackChannel?: string;
- phoneNumber?: string;
- provider?: string;
- };
- monitorIds: number[] | null; // null = all monitors
- triggerEvents: string[];
- cooldownMinutes: number;
- lastNotifiedAt: string | null;
- createdAt: string;
- updatedAt: string;
- createdBy: string;
-}
-
-// Channels API
-async function getChannels() {
- return authedFetch<{ channels: NotificationChannel[] }>("/uptime/notification-channels");
-}
-
-async function createChannel(data: {
- type: NotificationChannel["type"];
- name: string;
- config: NotificationChannel["config"];
- monitorIds?: number[] | null;
- triggerEvents?: string[];
- cooldownMinutes?: number;
-}) {
- return authedFetch(`/uptime/notification-channels`, undefined, { method: "POST", data });
-}
-
-async function updateChannel(
- id: number,
- data: {
- name?: string;
- enabled?: boolean;
- config?: NotificationChannel["config"];
- monitorIds?: number[] | null;
- triggerEvents?: string[];
- cooldownMinutes?: number;
- }
-) {
- return authedFetch(`/uptime/notification-channels/${id}`, undefined, { method: "PUT", data });
-}
-
-async function deleteChannel(id: number) {
- return authedFetch(`/uptime/notification-channels/${id}`, undefined, { method: "DELETE" });
-}
-
-async function testChannel(id: number) {
- return authedFetch(`/uptime/notification-channels/${id}/test`, undefined, { method: "POST", data: {} });
-}
-
-// Hooks
-export function useNotificationChannels() {
- return useQuery({
- queryKey: ["notification-channels"],
- queryFn: getChannels,
- });
-}
-
-export function useCreateChannel() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: createChannel,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
- },
- });
-}
-
-export function useUpdateChannel() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: ({ id, data }: { id: number; data: Parameters<typeof updateChannel>[1] }) => updateChannel(id, data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
- },
- });
-}
-
-export function useDeleteChannel() {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: deleteChannel,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["notification-channels"] });
- },
- });
-}
-
-export function useTestChannel() {
- return useMutation({
- mutationFn: testChannel,
- });
-}
diff --git a/client/src/app/uptime/incidents/page.tsx b/client/src/app/uptime/incidents/page.tsx
deleted file mode 100644
index f7285cb75..000000000
--- a/client/src/app/uptime/incidents/page.tsx
+++ /dev/null
@@ -1,251 +0,0 @@
-"use client";
-
-import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { useDateTimeFormat } from "@/hooks/useDateTimeFormat";
-import { getTimezone } from "@/lib/store";
-import { cn } from "@/lib/utils";
-import { AlertCircle, CheckCircle, MoreHorizontal } from "lucide-react";
-import { DateTime } from "luxon";
-import { useState } from "react";
-import { toast } from "@/components/ui/sonner";
-import {
- UptimeIncident,
- useAcknowledgeIncident,
- useIncidents,
- useResolveIncident,
-} from "../../../api/uptime/incidents";
-
-const getStatusIcon = (status: UptimeIncident["status"]) => {
- switch (status) {
- case "active":
- return (
- <div className="p-2 rounded-lg bg-red-500/10">
- <AlertCircle className="w-4 h-4 text-red-500" />
- </div>
- );
- case "acknowledged":
- return (
- <div className="p-2 rounded-lg bg-yellow-500/10">
- <AlertCircle className="w-4 h-4 text-yellow-500" />
- </div>
- );
- case "resolved":
- return (
- <div className="p-2 rounded-lg bg-green-500/10">
- <CheckCircle className="w-4 h-4 text-green-500" />
- </div>
- );
- }
-};
-
-const formatDuration = (startTime: string, endTime: string | null): string => {
- const start = DateTime.fromSQL(startTime, { zone: "UTC" });
- const end = endTime ? DateTime.fromSQL(endTime, { zone: "UTC" }) : DateTime.now().toUTC();
- const diff = end.diff(start, ["days", "hours", "minutes", "seconds"]);
-
- const days = Math.floor(diff.days);
- const hours = Math.floor(diff.hours);
- const minutes = Math.floor(diff.minutes);
- const seconds = Math.floor(diff.seconds);
-
- let result = "";
- if (days > 0) {
- result = `${days}d ${hours % 24}h`;
- } else if (hours > 0) {
- result = `${hours}h ${minutes % 60}m`;
- } else if (minutes > 0) {
- result = `${minutes}m`;
- } else {
- result = `${seconds}s`;
- }
-
- return endTime ? result : `${result} (ongoing)`;
-};
-
-export default function IncidentsPage() {
- const { formatRelative } = useDateTimeFormat();
-
- const formatStartTime = (timestamp: string) => {
- const dt = DateTime.fromSQL(timestamp, { zone: "UTC" }).setZone(getTimezone());
- return formatRelative(dt);
- };
-
- const [statusFilter, setStatusFilter] = useState<"active" | "acknowledged" | "resolved" | "all">("active");
-
- const { data, isLoading } = useIncidents({ status: statusFilter });
-
- const acknowledgeIncident = useAcknowledgeIncident();
- const resolveIncident = useResolveIncident();
-
- const handleAcknowledge = async (incident: UptimeIncident) => {
- try {
- await acknowledgeIncident.mutateAsync(incident.id);
- toast.success("Incident acknowledged");
- } catch (error) {
- toast.error("Failed to acknowledge incident");
- }
- };
-
- const handleResolve = async (incident: UptimeIncident) => {
- try {
- await resolveIncident.mutateAsync(incident.id);
- toast.success("Incident resolved");
- } catch (error) {
- toast.error("Failed to resolve incident");
- }
- };
-
- return (
- <>
- <div className="flex items-center justify-between mb-6">
- <h1 className="text-2xl font-semibold">Incidents</h1>
-
- <Tabs value={statusFilter} onValueChange={value => setStatusFilter(value as any)}>
- <TabsList>
- <TabsTrigger value="active">Active</TabsTrigger>
- <TabsTrigger value="acknowledged">Acknowledged</TabsTrigger>
- <TabsTrigger value="resolved">Resolved</TabsTrigger>
- <TabsTrigger value="all">All</TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
-
- <div className="rounded-lg border border-neutral-800">
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead className="w-10"></TableHead>
- <TableHead>Monitor Name</TableHead>
- <TableHead>Affected Regions</TableHead>
- <TableHead>Start Time</TableHead>
- <TableHead>Duration</TableHead>
- <TableHead className="w-10"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {isLoading ? (
- Array.from({ length: 5 }).map((_, i) => (
- <TableRow key={`skeleton-${i}`}>
- <TableCell>
- <Skeleton className="h-4 w-4 rounded-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-48" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-32" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-32" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-24" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-8 w-8" />
- </TableCell>
- </TableRow>
- ))
- ) : data?.incidents?.length === 0 ? (
- <TableRow>
- <TableCell colSpan={6} className="text-center py-8 text-neutral-500">
- No incidents found
- </TableCell>
- </TableRow>
- ) : (
- data?.incidents?.map(incident => (
- <TableRow key={incident.id}>
- <TableCell>{getStatusIcon(incident.status)}</TableCell>
- <TableCell>
- <div className="font-medium">{incident.monitorName}</div>
- </TableCell>
- <TableCell>
- {incident.affectedRegions && incident.affectedRegions.length > 0 ? (
- <div className="flex flex-wrap gap-1">
- {incident.affectedRegions.length > 3 ? (
- <>
- {incident.affectedRegions.slice(0, 3).map(region => (
- <span
- key={region}
- className={cn(
- "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
- region === "global" ? "bg-red-500/20 text-red-400" : "bg-neutral-700 text-neutral-300"
- )}
- >
- {region.toUpperCase()}
- </span>
- ))}
- <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full bg-neutral-700 text-neutral-300">
- +{incident.affectedRegions.length - 3} more
- </span>
- </>
- ) : (
- incident.affectedRegions.map(region => (
- <span
- key={region}
- className={cn(
- "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
- region === "global" ? "bg-red-500/20 text-red-400" : "bg-neutral-700 text-neutral-300"
- )}
- >
- {region.toUpperCase()}
- </span>
- ))
- )}
- </div>
- ) : incident.region ? (
- <span
- className={cn(
- "inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full",
- incident.region === "global"
- ? "bg-red-500/20 text-red-400"
- : "bg-neutral-700 text-neutral-300"
- )}
- >
- {incident.region.toUpperCase()}
- </span>
- ) : (
- <span className="text-neutral-500">-</span>
- )}
- </TableCell>
- <TableCell className="text-sm text-neutral-300">{formatStartTime(incident.startTime)}</TableCell>
- <TableCell>
- <div className="text-sm text-neutral-300">
- {formatDuration(incident.startTime, incident.endTime || null)}
- </div>
- </TableCell>
- <TableCell>
- <DropdownMenu>
- <DropdownMenuTrigger asChild disabled={incident.status === "resolved"}>
- <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {incident.status === "active" && (
- <DropdownMenuItem onClick={() => handleAcknowledge(incident)}>Acknowledge</DropdownMenuItem>
- )}
- {incident.status !== "resolved" && (
- <DropdownMenuItem onClick={() => handleResolve(incident)}>Resolve</DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
- </div>
- </>
- );
-}
diff --git a/client/src/app/uptime/layout.tsx b/client/src/app/uptime/layout.tsx
deleted file mode 100644
index 63d701e10..000000000
--- a/client/src/app/uptime/layout.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client";
-
-import { useWindowSize } from "@uidotdev/usehooks";
-import { AppSidebar } from "../../components/AppSidebar";
-import { MobileSidebar } from "./monitors/components/Sidebar/MobileSidebar";
-import { StandardPage } from "../../components/StandardPage";
-import { UptimeSidebar } from "./monitors/components/Sidebar/UptimeSidebar";
-
-export default function UptimeLayout({ children }: { children: React.ReactNode }) {
- const { width } = useWindowSize();
-
- if (width && width < 768) {
- return (
- <StandardPage showSidebar={false}>
- <MobileSidebar />
- <div className="mt-4">{children}</div>
- </StandardPage>
- );
- }
-
- return (
- <div className="flex h-full">
- <AppSidebar />
- <UptimeSidebar />
- <StandardPage showSidebar={false}>
- <div className="flex-1 overflow-auto mt-4">{children}</div>
- </StandardPage>
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx
deleted file mode 100644
index cc5a20dd2..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/EventDetailsRow.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import { MonitorEvent } from "@/api/uptime/monitors";
-import { TimingWaterfall } from "./TimingWaterfall";
-
-interface EventDetailsRowProps {
- event: MonitorEvent;
-}
-
-export function EventDetailsRow({ event }: EventDetailsRowProps) {
- return (
- <div className="bg-neutral-900 border-t border-neutral-800 p-6">
- <div className="space-y-6">
- {/* Timing Waterfall */}
- {event.monitor_type === "http" && (
- <div className="mb-6">
- <TimingWaterfall event={event} />
- </div>
- )}
-
- {/* Error Message */}
- {event.error_message && (
- <div>
- <h4 className="text-sm font-medium text-red-500 mb-2">Error Message</h4>
- <div className="text-sm text-neutral-400 bg-neutral-900 p-3 rounded whitespace-pre-wrap font-mono">
- {event.error_message}
- </div>
- </div>
- )}
-
- {/* Headers Table */}
- {event.response_headers && Object.keys(event.response_headers).length > 0 && (
- <div>
- <h4 className="text-sm font-medium mb-2">Response Headers</h4>
- <div className="border border-neutral-800 rounded overflow-hidden">
- <table className="w-full text-xs">
- <tbody>
- {Object.entries(event.response_headers).map(([key, value], index) => (
- <tr
- key={key}
- className={cn(
- "border-b border-neutral-800",
- index === Object.keys(event.response_headers!).length - 1 && "border-b-0"
- )}
- >
- <td className="px-4 py-2 text-neutral-400 font-mono w-1/3 bg-neutral-900/50">{key}</td>
- <td className="px-4 py-2 text-neutral-200 font-mono break-all">{value}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx b/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
deleted file mode 100644
index 8c4374184..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/EventsTable.tsx
+++ /dev/null
@@ -1,264 +0,0 @@
-"use client";
-
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getFilteredRowModel,
- getSortedRowModel,
- SortingState,
- useReactTable,
-} from "@tanstack/react-table";
-import { getTimezone } from "@/lib/store";
-import { Loader2 } from "lucide-react";
-import { DateTime } from "luxon";
-import React, { useMemo, useState } from "react";
-import { MonitorEvent, UptimeMonitor, useMonitorEventsInfinite } from "../../../../../api/uptime/monitors";
-import { Badge } from "../../../../../components/ui/badge";
-import { Button } from "../../../../../components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "../../../../../components/ui/card";
-import { Skeleton } from "../../../../../components/ui/skeleton";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../components/ui/table";
-import { CountryFlag } from "../../../../[site]/components/shared/icons/CountryFlag";
-import { useUptimeStore } from "../../components/uptimeStore";
-import { REGIONS } from "../../const";
-import { EventDetailsRow } from "./EventDetailsRow";
-import { InlineTimingWaterfall } from "./InlineTimingWaterfall";
-
-const columnHelper = createColumnHelper<MonitorEvent>();
-
-export function EventsTable({ monitor, monitorId }: { monitor?: UptimeMonitor; monitorId: number }) {
- const [sorting, setSorting] = useState<SortingState>([]);
- const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
- const { selectedRegion } = useUptimeStore();
-
- const {
- data,
- isLoading: isLoadingEvents,
- isFetchingNextPage,
- hasNextPage,
- fetchNextPage,
- } = useMonitorEventsInfinite(monitorId, {
- region: selectedRegion,
- });
-
- // Flatten all pages of events
- const allEvents = useMemo(() => {
- return data?.pages.flatMap(page => page.events) || [];
- }, [data]);
-
- const toggleRow = (rowId: string) => {
- const newExpanded = new Set(expandedRows);
- if (newExpanded.has(rowId)) {
- newExpanded.delete(rowId);
- } else {
- newExpanded.add(rowId);
- }
- setExpandedRows(newExpanded);
- };
-
- const columns = useMemo(
- () => [
- columnHelper.display({
- id: "status",
- header: () => <div className="w-8"></div>,
- cell: ({ row }) => (
- <div className="flex justify-center">
- {row.original.status === "success" ? (
- <div className="w-2 h-2 bg-green-500 rounded-full" />
- ) : (
- <div className="w-2 h-2 bg-red-500 rounded-full" />
- )}
- </div>
- ),
- size: 40,
- }),
- columnHelper.accessor("timestamp", {
- header: "Time",
- cell: ({ row }) => {
- const timestamp = DateTime.fromSQL(row.original.timestamp, { zone: "utc" });
- return (
- <div className="text-sm">
- <div className="">{timestamp.setZone(getTimezone()).toFormat("MMM dd, HH:mm:ss")}</div>
- </div>
- );
- },
- }),
- columnHelper.accessor("status_code", {
- header: "Status",
- cell: ({ row }) => {
- const code = row.original.status_code;
- if (!code) return <span className="text-neutral-500">-</span>;
-
- if (code >= 500) {
- return <Badge variant="destructive">{code}</Badge>;
- }
- if (code >= 400) {
- return <Badge variant="warning">{code}</Badge>;
- }
- if (code >= 300) {
- return <Badge variant="info">{code}</Badge>;
- }
- if (code >= 200) {
- return <Badge variant="success">{code}</Badge>;
- }
- return <Badge variant="secondary">{code}</Badge>;
- },
- }),
- columnHelper.accessor("response_time_ms", {
- header: "Latency",
- cell: ({ row }) => (
- <span className="font-mono text-sm">
- {row.original.response_time_ms ? `${Math.round(row.original.response_time_ms)}ms` : "-"}
- </span>
- ),
- }),
- columnHelper.display({
- id: "timings",
- header: "Timings",
- cell: ({ row }) => <InlineTimingWaterfall event={row.original} />,
- }),
- // Conditionally add region column for global monitoring
- ...(monitor?.monitoringType === "global"
- ? [
- columnHelper.accessor("region", {
- header: "Region",
- cell: ({ row }) => {
- const region = REGIONS.find(r => r.code === row.original.region);
- return (
- <span className="text-sm flex items-center gap-2">
- <CountryFlag country={region?.countryCode || "US"} className="w-5 h-5" />
- <span className="text-sm">{region?.name || "-"}</span>
- </span>
- );
- },
- }),
- ]
- : []),
- ],
- [monitor?.monitoringType]
- );
-
- // Create table instance
- const table = useReactTable({
- data: allEvents,
- columns,
- state: {
- sorting,
- },
- onSortingChange: setSorting,
- getCoreRowModel: getCoreRowModel(),
- getFilteredRowModel: getFilteredRowModel(),
- getSortedRowModel: getSortedRowModel(),
- manualPagination: true,
- });
-
- return (
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Recent Events</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="rounded-lg border border-neutral-800">
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map(headerGroup => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <TableHead
- key={header.id}
- style={{
- width: header.getSize() === 150 ? undefined : header.getSize(),
- }}
- >
- {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
- </TableHead>
- ))}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {isLoadingEvents ? (
- Array.from({ length: 10 }).map((_, i) => (
- <TableRow key={`skeleton-${i}`}>
- {/* Status dot */}
- <TableCell className="w-10">
- <div className="flex justify-center">
- <Skeleton className="h-2 w-2 rounded-full" />
- </div>
- </TableCell>
- {/* Time */}
- <TableCell>
- <Skeleton className="h-4 w-32" />
- </TableCell>
- {/* Status Code */}
- <TableCell>
- <Skeleton className="h-6 w-12" />
- </TableCell>
- {/* Latency */}
- <TableCell>
- <Skeleton className="h-4 w-16" />
- </TableCell>
- {/* Timings */}
- <TableCell>
- <Skeleton className="h-3 w-24" />
- </TableCell>
- {/* Region - only show for global monitoring */}
- {monitor?.monitoringType === "global" && (
- <TableCell>
- <Skeleton className="h-4 w-12" />
- </TableCell>
- )}
- </TableRow>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
- <TableRow>
- <TableCell colSpan={columns.length} className="text-center text-neutral-500 py-8">
- No events found
- </TableCell>
- </TableRow>
- ) : (
- table.getRowModel().rows.map(row => (
- <React.Fragment key={row.id}>
- <TableRow className="cursor-pointer hover:bg-neutral-900/50" onClick={() => toggleRow(row.id)}>
- {row.getVisibleCells().map(cell => (
- <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
- ))}
- </TableRow>
-
- {expandedRows.has(row.id) && (
- <TableRow>
- <TableCell colSpan={columns.length} className="p-0">
- <EventDetailsRow event={row.original} />
- </TableCell>
- </TableRow>
- )}
- </React.Fragment>
- ))
- )}
- </TableBody>
- </Table>
- </div>
-
- {/* Infinite scroll loader */}
- {isFetchingNextPage && (
- <div className="flex justify-center">
- <Button variant="ghost" size="sm" disabled>
- <Loader2 className="h-4 w-4 animate-spin" />
- Loading more events&hellip;
- </Button>
- </div>
- )}
-
- {/* Load more button (as fallback) */}
- {hasNextPage && !isFetchingNextPage && (
- <div className="flex justify-center">
- <Button variant="outline" size="sm" onClick={() => fetchNextPage()}>
- Load More
- </Button>
- </div>
- )}
- </CardContent>
- </Card>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx b/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx
deleted file mode 100644
index 46d321787..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/FilterBar.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import { CountryFlag } from "@/app/[site]/components/shared/icons/CountryFlag";
-import { Button } from "@/components/ui/button";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Earth } from "lucide-react";
-import { UptimeMonitor } from "../../../../../api/uptime/monitors";
-import { TIME_RANGES, useUptimeStore } from "../../components/uptimeStore";
-import { REGIONS } from "../../const";
-
-interface FilterBarProps {
- monitor?: UptimeMonitor;
- isLoading: boolean;
-}
-
-export function FilterBar({ monitor, isLoading }: FilterBarProps) {
- const { timeRange, setTimeRange, selectedRegion, setSelectedRegion } = useUptimeStore();
-
- // Only show region filter for global monitors (multi-region)
- const showRegionFilter = monitor?.monitoringType === "global";
-
- return (
- <div className="flex items-center gap-2 justify-between">
- {/* Time Range Selector */}
- <div className="flex items-center gap-1">
- {TIME_RANGES.map(range => (
- <Button
- key={range.value}
- variant={timeRange === range.value ? "default" : "ghost"}
- size="sm"
- onClick={() => setTimeRange(range.value)}
- className="h-7 px-2 text-xs"
- >
- {range.label}
- </Button>
- ))}
- </div>
-
- {/* Region Filter - only show for multi-region monitors */}
- {showRegionFilter && !isLoading && (
- <Select
- value={selectedRegion || "all"}
- onValueChange={value => setSelectedRegion(value === "all" ? undefined : value)}
- >
- <SelectTrigger size="sm" className="w-[140px] ml-2">
- <SelectValue placeholder="Select region" />
- </SelectTrigger>
- <SelectContent size="sm">
- {REGIONS.filter((region, i) => i === 0 || monitor?.selectedRegions.includes(region.code)).map(region => (
- <SelectItem key={region.code} value={region.code} size="sm">
- <div className="flex items-center gap-2">
- {region.countryCode ? (
- <CountryFlag country={region.countryCode} className="w-4 h-3" />
- ) : (
- <Earth className="w-4 h-4" />
- )}
- <span>{region.name}</span>
- </div>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx b/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx
deleted file mode 100644
index 6f997b022..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/InlineTimingWaterfall.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import { MonitorEvent } from "@/api/uptime/monitors";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { getTimingSegments, renderTimingSegments, TimingSegment } from "./timingUtils";
-
-interface InlineTimingWaterfallProps {
- event: MonitorEvent;
-}
-
-function renderInlineSegment(
- timing: TimingSegment,
- props: { left: number; width: number; zIndex: number; index: number }
-) {
- return (
- <Tooltip key={timing.label}>
- <TooltipTrigger asChild>
- <div
- className={cn("absolute h-full", timing.color)}
- style={{
- left: `${props.left}%`,
- width: `${props.width}%`,
- zIndex: props.zIndex,
- }}
- />
- </TooltipTrigger>
- <TooltipContent side="top" className="text-xs">
- <div className="font-medium">{timing.label}</div>
- <div className="font-mono">{timing.time}ms</div>
- </TooltipContent>
- </Tooltip>
- );
-}
-
-export function InlineTimingWaterfall({ event }: InlineTimingWaterfallProps) {
- const timings = getTimingSegments(event);
- const totalTime = event.response_time_ms || 0;
-
- if (timings.length === 0 || totalTime === 0) {
- return <div className="w-24 h-3" />;
- }
-
- return (
- <TooltipProvider>
- <div className="relative h-3 w-40 bg-neutral-800 rounded overflow-hidden">
- {renderTimingSegments(timings, totalTime, renderInlineSegment)}
- </div>
- </TooltipProvider>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx b/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx
deleted file mode 100644
index ecc786ecb..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/TimingWaterfall.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-"use client";
-
-import { cn } from "@/lib/utils";
-import { MonitorEvent } from "@/api/uptime/monitors";
-import { getTimingSegments, renderTimingSegments, TimingSegment } from "./timingUtils";
-
-interface TimingWaterfallProps {
- event: MonitorEvent;
-}
-
-function renderWaterfallSegment(
- timing: TimingSegment,
- props: { left: number; width: number; zIndex: number; index: number }
-) {
- return (
- <div
- key={timing.label}
- className={cn("absolute h-full", timing.color)}
- style={{
- left: `${props.left}%`,
- width: `${props.width}%`,
- zIndex: props.zIndex,
- }}
- title={`${timing.label}: ${timing.time}ms`}
- />
- );
-}
-
-function TimingLegendItem({ timing }: { timing: TimingSegment }) {
- return (
- <div className="flex items-center gap-1 text-xs">
- <div className={cn("w-3 h-3 rounded", timing.color)} />
- <span className="text-neutral-400">{timing.label}:</span>
- <span className="font-mono">{timing.time}ms</span>
- </div>
- );
-}
-
-export function TimingWaterfall({ event }: TimingWaterfallProps) {
- const timings = getTimingSegments(event);
- const totalTime = event.response_time_ms || 0;
-
- if (timings.length === 0 || totalTime === 0) {
- return null;
- }
-
- return (
- <div className="w-full">
- <div className="text-sm font-medium mb-2">Timings</div>
- <div className="relative h-6 bg-neutral-800 rounded overflow-hidden">
- {renderTimingSegments(timings, totalTime, renderWaterfallSegment)}
- </div>
- <div className="flex flex-wrap gap-2 mt-2">
- {timings.map(timing => (
- <TimingLegendItem key={timing.label} timing={timing} />
- ))}
- </div>
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts b/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts
deleted file mode 100644
index 8d4e7e6eb..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/components/timingUtils.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { MonitorEvent } from "@/api/uptime/monitors";
-
-export interface TimingSegment {
- label: string;
- time: number | undefined;
- color: string;
-}
-
-export const TIMING_COLORS = {
- dns: "bg-emerald-500", // Green - similar to hsl(160, 70%, 50%)
- tcp: "bg-teal-500", // Turquoise - similar to hsl(180, 70%, 45%)
- tls: "bg-sky-500", // Light Blue - similar to hsl(200, 70%, 45%)
- ttfb: "bg-blue-500", // Blue - for TTFB (not in chart but fits the gradient)
- transfer: "bg-indigo-500", // Deeper Blue - similar to hsl(220, 70%, 50%)
-} as const;
-
-export function getTimingSegments(event: MonitorEvent): TimingSegment[] {
- return [
- { label: "DNS", time: event.dns_time_ms, color: TIMING_COLORS.dns },
- { label: "TCP", time: event.tcp_time_ms, color: TIMING_COLORS.tcp },
- { label: "TLS", time: event.tls_time_ms, color: TIMING_COLORS.tls },
- { label: "TTFB", time: event.ttfb_ms, color: TIMING_COLORS.ttfb },
- { label: "Transfer", time: event.transfer_time_ms, color: TIMING_COLORS.transfer },
- ].filter(t => t.time && t.time > 0);
-}
-
-export function calculateTimingMetrics(timings: TimingSegment[], totalTime: number) {
- const sumOfTimings = timings.reduce((sum, t) => sum + (t.time || 0), 0);
- const needsNormalization = sumOfTimings > totalTime;
-
- return {
- sumOfTimings,
- needsNormalization,
- };
-}
-
-export function calculateSegmentWidth(
- timing: TimingSegment,
- totalTime: number,
- sumOfTimings: number,
- needsNormalization: boolean
-): number {
- if (!timing.time) return 0;
-
- return needsNormalization ? (timing.time / sumOfTimings) * 100 : (timing.time / totalTime) * 100;
-}
-
-export function renderTimingSegments(
- timings: TimingSegment[],
- totalTime: number,
- renderSegment: (
- segment: TimingSegment,
- props: {
- left: number;
- width: number;
- zIndex: number;
- index: number;
- }
- ) => React.ReactNode
-): React.ReactNode[] {
- const { sumOfTimings, needsNormalization } = calculateTimingMetrics(timings, totalTime);
-
- let left = 0;
- return timings.map((timing, index) => {
- const width = calculateSegmentWidth(timing, totalTime, sumOfTimings, needsNormalization);
- const adjustedWidth = Math.min(width, 100 - left);
-
- const element = renderSegment(timing, {
- left,
- width: adjustedWidth,
- zIndex: timings.length - index,
- index,
- });
-
- left += adjustedWidth;
- return element;
- });
-}
diff --git a/client/src/app/uptime/monitors/[monitorId]/page.tsx b/client/src/app/uptime/monitors/[monitorId]/page.tsx
deleted file mode 100644
index 6b9861153..000000000
--- a/client/src/app/uptime/monitors/[monitorId]/page.tsx
+++ /dev/null
@@ -1,182 +0,0 @@
-"use client";
-
-import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-import { cn } from "@/lib/utils";
-import { ArrowLeft } from "lucide-react";
-import { useParams, useRouter } from "next/navigation";
-import { UptimeMonitor, useMonitor, useMonitorStats, useMonitorUptime } from "../../../../api/uptime/monitors";
-import { StandardPage } from "../../../../components/StandardPage";
-import { INTERVAL_OPTIONS } from "../components/dialog/GeneralTab";
-import { MonitorActions } from "../components/MonitorActions";
-import { MonitorResponseTimeChart } from "../components/MonitorResponseTimeChart";
-import { StatusOrb } from "../components/StatusOrb";
-import { useUptimeStore } from "../components/uptimeStore";
-import { getHoursFromTimeRange } from "../components/utils";
-import { EventsTable } from "./components/EventsTable";
-import { FilterBar } from "./components/FilterBar";
-
-interface StatCardProps {
- label: string;
- value: string;
- isLoading?: boolean;
-}
-
-const formatResponseTime = (value?: number) => {
- if (!value) return "-";
- return `${Math.round(value)}ms`;
-};
-
-const formatPercentage = (value?: number) => {
- if (!value) return "-";
- return `${value.toFixed(1)}%`;
-};
-
-const formatUptime = (seconds?: number) => {
- if (!seconds) return "-";
- const days = Math.floor(seconds / 86400);
- const hours = Math.floor((seconds % 86400) / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
-
- if (days > 0) {
- return `${days}d ${hours}h`;
- }
- if (hours > 0) {
- return `${hours}h ${minutes}m`;
- }
- return `${minutes}m`;
-};
-
-const formatInterval = (seconds?: number) => {
- const interval = INTERVAL_OPTIONS.find(interval => interval.value === seconds);
- return interval?.label || `${seconds}s`;
-};
-
-function StatCard({ label, value, isLoading }: StatCardProps) {
- return (
- <div className="bg-neutral-900 rounded-lg border border-neutral-850">
- <div className="p-3 pb-0 text-sm text-neutral-500 flex items-center gap-2 font-normal">{label}</div>
- <div className="p-3 py-2">
- {isLoading ? <Skeleton className="h-7 w-24" /> : <p className="text-xl font-semibold">{value}</p>}
- </div>
- </div>
- );
-}
-
-const getMonitorName = (monitor: UptimeMonitor) => {
- return (
- monitor.name ||
- (monitor.monitorType === "http" ? monitor.httpConfig?.url : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`)
- );
-};
-
-const MonitorHeader = ({ monitor, isLoadingMonitor }: { monitor?: UptimeMonitor; isLoadingMonitor: boolean }) => {
- if (isLoadingMonitor) {
- return (
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-3">
- <Skeleton className="h-7 w-64" /> {/* Monitor name */}
- <Skeleton className="h-4 w-4 rounded-full" /> {/* Status orb */}
- </div>
- <div className="flex items-center gap-2 mt-1">
- <Skeleton className="h-4 w-4" /> {/* Status text */}
- <span className="text-neutral-500">β€’</span>
- <Skeleton className="h-4 w-40" /> {/* URL/host */}
- <span className="text-neutral-500">β€’</span>
- <Skeleton className="h-4 w-28" /> {/* Interval */}
- </div>
- </div>
- );
- }
- if (!monitor) return null;
- return (
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-3">
- <h1 className="text-2xl font-semibold">{getMonitorName(monitor)}</h1>
- <StatusOrb status={monitor.status?.currentStatus || "unknown"} size="lg" />
- </div>
- <p className="text-sm text-neutral-300 mt-1 flex items-center gap-2">
- <span
- className={cn("font-medium", monitor.status?.currentStatus === "up" ? "text-green-400" : "text-red-500/80")}
- >
- {monitor.status?.currentStatus === "up" ? "Up" : "Down"}
- </span>
- β€’
- <span>
- {monitor.monitorType === "http"
- ? monitor.httpConfig?.url
- : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`}
- </span>
- β€’<span>every {formatInterval(monitor.intervalSeconds)}</span>
- </p>
- </div>
- );
-};
-
-export default function MonitorDetailPage() {
- const params = useParams();
- const router = useRouter();
- const monitorId = parseInt(params.monitorId as string);
-
- const { timeRange, selectedRegion } = useUptimeStore();
- const { data: monitor, isLoading: isLoadingMonitor } = useMonitor(monitorId);
- const { data: stats, isLoading: isLoadingStats } = useMonitorStats(monitorId, {
- hours: getHoursFromTimeRange(timeRange),
- region: selectedRegion,
- });
-
- const { data: uptimeData, isLoading: isLoadingUptime } = useMonitorUptime(monitorId);
-
- if (!monitor && !isLoadingMonitor) {
- return (
- <StandardPage showSidebar={false}>
- <div className="text-center py-12">
- <h2 className="text-xl font-semibold mb-2">Monitor not found</h2>
- <Button onClick={() => router.push("/uptime")} variant="outline">
- Back to Monitors
- </Button>
- </div>
- </StandardPage>
- );
- }
-
- return (
- <>
- <div className="space-y-4">
- {/* Header */}
- <Button
- variant="ghost"
- size="sm"
- onClick={() => router.push("/uptime/monitors")}
- className="flex items-center gap-2"
- >
- <ArrowLeft className="h-4 w-4" />
- Back
- </Button>
- <div className="flex items-start justify-between">
- <MonitorHeader monitor={monitor} isLoadingMonitor={isLoadingMonitor} />
- <MonitorActions monitor={monitor} />
- </div>
- <FilterBar monitor={monitor} isLoading={isLoadingMonitor} />
-
- {/* Stats Grid */}
- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
- <StatCard label="Uptime" value={formatPercentage(stats?.stats.uptimePercentage)} isLoading={isLoadingStats} />
- <StatCard
- label="Current Uptime"
- value={formatUptime(uptimeData?.currentUptimeSeconds)}
- isLoading={isLoadingUptime}
- />
- <StatCard label="P50" value={formatResponseTime(stats?.stats.responseTime.p50)} isLoading={isLoadingStats} />
- <StatCard label="P90" value={formatResponseTime(stats?.stats.responseTime.p90)} isLoading={isLoadingStats} />
- <StatCard label="P95" value={formatResponseTime(stats?.stats.responseTime.p95)} isLoading={isLoadingStats} />
- <StatCard label="P99" value={formatResponseTime(stats?.stats.responseTime.p99)} isLoading={isLoadingStats} />
- </div>
-
- {/* Response Time Chart */}
- <MonitorResponseTimeChart monitor={monitor} monitorId={monitorId} isLoading={isLoadingMonitor} />
- <EventsTable monitor={monitor} monitorId={monitorId} />
- </div>
- </>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/MonitorActions.tsx b/client/src/app/uptime/monitors/components/MonitorActions.tsx
deleted file mode 100644
index 242a33126..000000000
--- a/client/src/app/uptime/monitors/components/MonitorActions.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { Edit2, MoreVertical, Power, Trash2 } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "@/components/ui/sonner";
-import { UptimeMonitor, useDeleteMonitor, useUpdateMonitor } from "../../../../api/uptime/monitors";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "../../../../components/ui/alert-dialog";
-import { Button } from "../../../../components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "../../../../components/ui/dropdown-menu";
-import { cn } from "../../../../lib/utils";
-import { MonitorDialog } from "./dialog";
-
-export function MonitorActions({ monitor }: { monitor?: UptimeMonitor }) {
- const router = useRouter();
- const [showEditDialog, setShowEditDialog] = useState(false);
- const [showDeleteDialog, setShowDeleteDialog] = useState(false);
- const [isToggling, setIsToggling] = useState(false);
-
- const deleteMonitor = useDeleteMonitor();
- const updateMonitor = useUpdateMonitor();
-
- const handleToggle = async () => {
- if (!monitor) return;
-
- setIsToggling(true);
- try {
- await updateMonitor.mutateAsync({
- monitorId: monitor.id,
- data: { enabled: !monitor.enabled },
- });
- toast.success(`Monitor ${monitor.enabled ? "disabled" : "enabled"} successfully`);
- } catch (error: any) {
- toast.error(error.response?.data?.error || "Failed to update monitor");
- } finally {
- setIsToggling(false);
- }
- };
-
- const handleDelete = async () => {
- try {
- await deleteMonitor.mutateAsync(monitor?.id ?? 0);
- toast.success("Monitor deleted successfully");
- router.push("/uptime/monitors");
- } catch (error: any) {
- toast.error(error.response?.data?.error || "Failed to delete monitor");
- }
- };
-
- return (
- <>
- <div className="flex items-center gap-2">
- {monitor && (
- <Button
- size="sm"
- onClick={handleToggle}
- disabled={isToggling || !monitor}
- className={cn(
- "flex items-center gap-2",
- monitor?.enabled
- ? "dark:text-green-500 hover:dark:text-green-600"
- : "text-neutral-500 hover:text-neutral-400"
- )}
- >
- <Power className="h-4 w-4" />
- {monitor?.enabled ? "On" : "Off"}
- </Button>
- )}
- <Button size="sm" onClick={() => setShowEditDialog(true)} className="flex items-center gap-2">
- <Edit2 className="h-4 w-4" />
- Edit
- </Button>
-
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
- <MoreVertical className="h-4 w-4" />
- <span className="sr-only">Open menu</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setShowDeleteDialog(true)} className="text-red-500 focus:text-red-600">
- <Trash2 className="h-4 w-4" />
- Delete Monitor
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- {monitor && <MonitorDialog monitor={monitor} open={showEditDialog} onOpenChange={setShowEditDialog} />}
-
- {/* Delete Confirmation */}
- <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This will permanently delete the monitor "
- {monitor?.name ||
- (monitor?.monitorType === "http"
- ? monitor?.httpConfig?.url
- : `${monitor?.tcpConfig?.host}:${monitor?.tcpConfig?.port}`)}
- " and all its historical data. This action cannot be undone.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction onClick={handleDelete} variant={"destructive"}>
- Delete Monitor
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx b/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
deleted file mode 100644
index a07ccd8a9..000000000
--- a/client/src/app/uptime/monitors/components/MonitorResponseTimeChart.tsx
+++ /dev/null
@@ -1,430 +0,0 @@
-"use client";
-
-import { UptimeMonitor, useMonitorStats } from "@/api/uptime/monitors";
-import { ChartTooltip } from "@/components/charts/ChartTooltip";
-import { Card, CardContent } from "@/components/ui/card";
-import { Skeleton } from "@/components/ui/skeleton";
-import { formatChartDateTime, hour12, userLocale } from "@/lib/dateTimeUtils";
-import { getTimezone } from "@/lib/store";
-import { cn } from "@/lib/utils";
-import { ResponsiveLine } from "@nivo/line";
-import { DateTime } from "luxon";
-import { useEffect, useState } from "react";
-import { useNivoTheme } from "../../../../lib/nivo";
-import { UptimeBucketSelection } from "./UptimeBucketSelection";
-import { useUptimeStore } from "./uptimeStore";
-import { getHoursFromTimeRange } from "./utils";
-
-const MONITOR_COLORS = {
- dns: "hsl(160, 70%, 50%)",
- connection: "hsl(180, 70%, 45%)",
- tls: "hsl(200, 70%, 45%)",
- transfer: "hsl(220, 70%, 50%)",
-} as const;
-
-// HTTP timing metrics with labels for stacked view - gradient from green-turquoise to blue
-const HTTP_METRICS = [
- { key: "dns_time_ms", label: "DNS", color: MONITOR_COLORS.dns }, // Green
- { key: "tcp_time_ms", label: "Connection", color: MONITOR_COLORS.connection }, // Turquoise
- { key: "tls_time_ms", label: "TLS Handshake", color: MONITOR_COLORS.tls }, // Light Blue
- { key: "transfer_time_ms", label: "Data Transfer", color: MONITOR_COLORS.transfer }, // Blue
-] as const;
-
-const formatTooltipValue = (value: number) => {
- return `${Math.round(value)}ms`;
-};
-
-export function MonitorResponseTimeChart({
- monitor,
- monitorId,
- isLoading: isLoadingMonitor,
-}: {
- monitor?: UptimeMonitor;
- monitorId: number;
- isLoading: boolean;
-}) {
- const monitorType = monitor?.monitorType;
-
- const { timeRange, bucket, setBucket, selectedRegion } = useUptimeStore();
-
- const [visibleMetrics, setVisibleMetrics] = useState<Set<string>>(new Set());
-
- useEffect(() => {
- if (monitorType === "http") {
- setVisibleMetrics(new Set(HTTP_METRICS.map(m => m.key)));
- } else {
- setVisibleMetrics(new Set(["response_time_ms"]));
- }
- }, [monitorType]);
-
- const { data: statsData, isLoading } = useMonitorStats(monitorId, {
- hours: getHoursFromTimeRange(timeRange),
- bucket,
- region: selectedRegion,
- });
-
- const toggleMetric = (metricKey: string) => {
- setVisibleMetrics(prev => {
- const newSet = new Set(prev);
- if (newSet.has(metricKey)) {
- newSet.delete(metricKey);
- } else {
- newSet.add(metricKey);
- }
- return newSet;
- });
- };
-
- const timezone = getTimezone();
-
- // Process data for the chart
- const processedData =
- statsData?.distribution
- ?.map((item: any) => {
- if (!item.hour) return null;
-
- // Parse timestamp as UTC and keep in UTC for chart (useUTC: true)
- const timestamp = DateTime.fromSQL(item.hour, { zone: "utc" });
- if (!timestamp.isValid) return null;
-
- const dataPoint: any = {
- time: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"), // UTC format for chart
- timestamp: timestamp.toISO(), // Store ISO timestamp for proper timezone handling
- response_time_ms: item.avg_response_time,
- check_count: item.check_count || 0,
- success_count: item.success_count || 0,
- failure_count: item.failure_count || 0,
- timeout_count: item.timeout_count || 0,
- };
-
- // Calculate failure percentage
- dataPoint.failure_percentage =
- dataPoint.check_count > 0
- ? ((dataPoint.failure_count + dataPoint.timeout_count) / dataPoint.check_count) * 100
- : 0;
-
- // For HTTP monitors, include additional timing data
- if (monitorType === "http") {
- dataPoint.dns_time_ms = item.avg_dns_time || 0;
- dataPoint.tcp_time_ms = item.avg_tcp_time || 0;
- dataPoint.tls_time_ms = item.avg_tls_time || 0;
- dataPoint.ttfb_ms = item.avg_ttfb || 0;
- dataPoint.transfer_time_ms = item.avg_transfer_time || 0;
- }
-
- return dataPoint;
- })
- .filter((e: any) => e !== null)
- .reverse() ?? []; // Reverse to get chronological order (oldest first)
-
- // Create data series based on monitor type
- const createDataSeries = () => {
- if (monitorType === "tcp") {
- return [
- {
- id: "Response Time",
- color: "hsl(180, 70%, 45%)",
- data: processedData
- .map((item: any) => ({
- x: item.time,
- y: item.response_time_ms,
- }))
- .filter((point: any) => point.y !== null && point.y > 0),
- },
- ];
- }
-
- // For HTTP, show stacked timing metrics
- // Order matters for stacking - DNS first, then connection, TLS, and finally transfer
- return HTTP_METRICS.filter(metric => visibleMetrics.has(metric.key)).map(metric => ({
- id: metric.label,
- color: metric.color,
- data: processedData
- .map((item: any) => ({
- x: item.time,
- y: item[metric.key] || 0,
- }))
- .filter((point: any) => point.y !== null),
- }));
- };
-
- const data = createDataSeries();
-
- // Define gradients for stacked areas with lower opacity - gradient from green-turquoise to blue
- const defs =
- monitorType === "http"
- ? [
- {
- id: "gradientDNS",
- type: "linearGradient" as const,
- colors: [{ offset: 0, color: MONITOR_COLORS.dns, opacity: 0.1 }],
- },
- {
- id: "gradientConnection",
- type: "linearGradient" as const,
- colors: [{ offset: 0, color: MONITOR_COLORS.connection, opacity: 0.1 }],
- },
- {
- id: "gradientTLS",
- type: "linearGradient" as const,
- colors: [{ offset: 0, color: MONITOR_COLORS.tls, opacity: 0.1 }],
- },
- {
- id: "gradientTransfer",
- type: "linearGradient" as const,
- colors: [{ offset: 0, color: MONITOR_COLORS.transfer, opacity: 0.1 }],
- },
- ]
- : [];
-
- const fill =
- monitorType === "http"
- ? [
- { match: { id: "DNS" }, id: "gradientDNS" },
- { match: { id: "Connection" }, id: "gradientConnection" },
- { match: { id: "TLS Handshake" }, id: "gradientTLS" },
- { match: { id: "Data Transfer" }, id: "gradientTransfer" },
- ]
- : [];
-
- const formatXAxisValue = (value: Date) => {
- // Interpret JS Date as UTC, then convert to selected timezone
- const dt = DateTime.fromJSDate(value, { zone: "utc" }).setZone(timezone).setLocale(userLocale);
-
- // Format based on bucket size
- switch (bucket) {
- case "minute":
- case "five_minutes":
- case "ten_minutes":
- case "fifteen_minutes":
- return dt.toFormat(hour12 ? "h:mma" : "HH:mm");
- case "hour":
- if (timeRange === "24h") {
- return dt.toFormat(hour12 ? "ha" : "HH:mm");
- }
- return dt.toFormat(hour12 ? "MMM d, ha" : "dd MMM, HH:mm");
- case "day":
- return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
- case "week":
- return dt.toFormat("MMM d");
- case "month":
- return dt.toFormat("MMM yyyy");
- default:
- return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
- }
- };
- const nivoTheme = useNivoTheme();
-
- return (
- <Card className="overflow-visible">
- <CardContent className="p-4 overflow-visible">
- <div className="flex items-center justify-between mb-4">
- <h3 className="text-base font-medium">Response Time</h3>
-
- <div className="flex items-center gap-4">
- {/* Metric toggles for HTTP monitors */}
- {monitorType === "http" && (
- <div className="flex items-center gap-2">
- {HTTP_METRICS.map(metric => {
- const isVisible = visibleMetrics.has(metric.key);
- return (
- <button
- key={metric.key}
- onClick={() => toggleMetric(metric.key)}
- className={cn(
- "flex items-center space-x-1.5 px-2 py-1 rounded text-xs font-medium transition-all",
- isVisible
- ? "bg-neutral-800 text-white"
- : "bg-neutral-900 text-neutral-500 hover:text-neutral-400"
- )}
- >
- <div
- className={cn(
- "w-3 h-3 rounded-sm transition-opacity",
- isVisible ? "opacity-100" : "opacity-30"
- )}
- style={{ backgroundColor: metric.color }}
- />
- <span>{metric.label}</span>
- </button>
- );
- })}
- </div>
- )}
-
- {/* Time range and bucket selectors */}
- <div className="flex items-center gap-2">
- <UptimeBucketSelection timeRange={timeRange} bucket={bucket} onBucketChange={setBucket} />
- </div>
- </div>
- </div>
-
- {isLoadingMonitor || isLoading ? (
- <Skeleton className="w-full h-[400px] rounded-md" />
- ) : data.length === 0 || data.every(series => series.data.length === 0) ? (
- <div className="h-[400px] w-full flex items-center justify-center">
- <div className="text-center text-neutral-500">
- <p className="text-lg font-medium">No data available</p>
- <p className="text-sm">Try adjusting your time range</p>
- </div>
- </div>
- ) : (
- <div className="h-[400px] w-full relative" style={{ overflow: "visible", zIndex: 10 }}>
- <ResponsiveLine
- data={data}
- theme={nivoTheme}
- margin={{ top: 10, right: 20, bottom: 25, left: 50 }}
- defs={defs}
- fill={fill}
- xScale={{
- type: "time",
- precision: "second",
- format: "%Y-%m-%d %H:%M:%S",
- useUTC: true,
- }}
- yScale={{
- type: "linear",
- min: 0,
- stacked: monitorType === "http",
- reverse: false,
- }}
- enableGridX={false}
- enableGridY={true}
- gridYValues={5}
- axisTop={null}
- axisRight={null}
- axisBottom={{
- tickSize: 0,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- format: formatXAxisValue,
- }}
- axisLeft={{
- tickSize: 0,
- tickPadding: 10,
- tickRotation: 0,
- truncateTickAt: 0,
- tickValues: 5,
- format: value => `${value}ms`,
- }}
- colors={d => d.color}
- lineWidth={1}
- enablePoints={false}
- useMesh={true}
- animate={false}
- enableSlices="x"
- enableArea={monitorType === "http"}
- areaOpacity={0.7}
- layers={[
- "grid",
- "axes",
- "areas",
- // Custom layer for failure indicators - render AFTER areas and lines
- ({ innerHeight, xScale }) => (
- <>
- {processedData.map((point: any, index: number) => {
- if (point.failure_percentage === 0) return null;
-
- // Use the jsDate for proper timezone handling
- const x = xScale(point.jsDate);
-
- // Calculate width based on next point or use a default
- let width = 20; // Default width
- if (index < processedData.length - 1) {
- const nextPoint = processedData[index + 1];
- width = Math.abs(xScale(nextPoint.jsDate) - x);
- } else if (index > 0) {
- // For the last point, use the width from the previous interval
- const prevPoint = processedData[index - 1];
- width = Math.abs(x - xScale(prevPoint.jsDate));
- }
-
- // Determine color based on failure percentage
- let color = "hsla(48, 95%, 53%, 0.4)"; // Yellow for < 50%
- if (point.failure_percentage >= 50) {
- color = `hsla(0, 84%, 60%, 0.4)`; // Red for >= 50%
- }
-
- return (
- <rect
- key={`failure-${index}`}
- x={x}
- y={0}
- width={Math.max(1, Math.abs(width))}
- height={innerHeight}
- fill={color}
- />
- );
- })}
- </>
- ),
- "crosshair",
- "lines",
- "slices",
- "points",
- "mesh",
- "legends",
- ]}
- sliceTooltip={({ slice }: any) => {
- const currentTime = DateTime.fromJSDate(new Date(slice.points[0].data.x), { zone: "utc" }).setZone(timezone);
-
- // Find the corresponding data point to get failure info
- const dataPoint = processedData.find(
- (p: any) => DateTime.fromISO(p.timestamp).toMillis() === currentTime.toUTC().toMillis()
- );
-
- // For stacked HTTP charts, show cumulative total
- const total =
- monitorType === "http"
- ? slice.points.reduce((sum: number, point: any) => sum + Number(point.data.yFormatted), 0)
- : 0;
-
- return (
- <ChartTooltip>
- <div className="p-3 min-w-[200px]">
- <div className="mb-2">{formatChartDateTime(currentTime, bucket)}</div>
-
- {/* Show failure status if any failures */}
- {dataPoint && dataPoint.failure_percentage > 0 && (
- <div
- className={cn(
- "text-xs px-2 py-1 rounded mb-2",
- dataPoint.failure_percentage >= 50
- ? "bg-red-500/20 text-red-400"
- : "bg-yellow-500/20 text-yellow-400"
- )}
- >
- {dataPoint.failure_count + dataPoint.timeout_count} of {dataPoint.check_count} checks failed (
- {dataPoint.failure_percentage.toFixed(1)}%)
- </div>
- )}
-
- <div className="space-y-1.5 text-xs">
- {slice.points.map((point: any) => (
- <div key={point.seriesId} className="flex justify-between items-center">
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-sm" style={{ backgroundColor: point.seriesColor }} />
- <span>{point.seriesId}</span>
- </div>
- <span className="font-medium">{formatTooltipValue(Number(point.data.yFormatted))}</span>
- </div>
- ))}
- {monitorType === "http" && (
- <div className="flex justify-between items-center pt-1.5 border-t border-neutral-100 dark:border-neutral-750">
- <span>Total</span>
- <span className="font-semibold">{formatTooltipValue(total)}</span>
- </div>
- )}
- </div>
- </div>
- </ChartTooltip>
- );
- }}
- />
- </div>
- )}
- </CardContent>
- </Card>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/MonitorTableRow.tsx b/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
deleted file mode 100644
index fae69f928..000000000
--- a/client/src/app/uptime/monitors/components/MonitorTableRow.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import React from "react";
-import { DateTime } from "luxon";
-import { TableCell, TableRow } from "@/components/ui/table";
-import { getTimezone } from "@/lib/store";
-import { StatusOrb } from "./StatusOrb";
-import { UptimeBar } from "./UptimeBar";
-import { UptimeMonitor, useMonitorUptime } from "@/api/uptime/monitors";
-import { cn } from "@/lib/utils";
-import { Skeleton } from "@/components/ui/skeleton";
-
-interface MonitorTableRowProps {
- monitor: UptimeMonitor;
- onClick?: () => void;
-}
-
-const formatResponseTime = (value?: number) => {
- if (value === undefined || value === null) return "-";
- return `${Math.round(value)}ms`;
-};
-
-const formatPercentage = (value?: number) => {
- if (value === undefined || value === null) return "-";
- return `${value.toFixed(1)}%`;
-};
-
-const formatLastPing = (lastCheckedAt?: string) => {
- if (!lastCheckedAt) return "-";
-
- const lastPing = DateTime.fromSQL(lastCheckedAt, {
- zone: "utc",
- }).setZone(getTimezone());
-
- const now = DateTime.now();
- const diffMs = now.toMillis() - lastPing.toMillis();
-
- const seconds = Math.floor(diffMs / 1000);
- const minutes = Math.floor(seconds / 60);
- const hours = Math.floor(minutes / 60);
- const days = Math.floor(hours / 24);
-
- if (days > 0) return `${days}d ago`;
- if (hours > 0) return `${hours}h ago`;
- if (minutes > 0) return `${minutes}m ago`;
- if (seconds > 0) return `${seconds}s ago`;
- return "just now";
-};
-
-const formatUptime = (seconds: number): string => {
- const days = Math.floor(seconds / 86400);
- const hours = Math.floor((seconds % 86400) / 3600);
- const minutes = Math.floor((seconds % 3600) / 60);
-
- if (days > 0) {
- return `${days}d ${hours}h`;
- }
- if (hours > 0) {
- return `${hours}h ${minutes}m`;
- }
- return `${minutes}m`;
-};
-
-export function MonitorTableRow({ monitor, onClick }: MonitorTableRowProps) {
- const stats = monitor.status;
- const { data: uptimeData, isLoading: isLoadingUptime } = useMonitorUptime(monitor.id);
-
- return (
- <TableRow className="cursor-pointer hover:bg-neutral-900/50" onClick={onClick}>
- <TableCell className="text-center">
- <StatusOrb status={stats?.currentStatus || "unknown"} />
- </TableCell>
- <TableCell className="font-medium">
- <div>{monitor.name}</div>
- <div className="text-xs text-neutral-500">
- {monitor.monitorType === "http"
- ? monitor.httpConfig?.url
- : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`}
- </div>
- </TableCell>
- <TableCell>
- <span
- className={cn(
- "inline-flex items-center px-2 py-1 text-xs font-medium rounded-full",
- monitor.monitorType === "http" ? "bg-blue-500/20 text-blue-400" : "bg-purple-500/20 text-purple-400"
- )}
- >
- {monitor.monitorType.toUpperCase()}
- </span>
- </TableCell>
- <TableCell>
- <UptimeBar monitorId={monitor.id} />
- </TableCell>
- <TableCell>{formatLastPing(stats?.lastCheckedAt)}</TableCell>
- <TableCell className="text-right">{formatPercentage(stats?.uptimePercentage7d)}</TableCell>
- <TableCell className="text-right">
- {isLoadingUptime ? (
- <Skeleton className="h-4 w-16 inline-block" />
- ) : uptimeData ? (
- formatUptime(uptimeData.currentUptimeSeconds)
- ) : (
- "-"
- )}
- </TableCell>
- </TableRow>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/MonitorsTable.tsx b/client/src/app/uptime/monitors/components/MonitorsTable.tsx
deleted file mode 100644
index a562ca324..000000000
--- a/client/src/app/uptime/monitors/components/MonitorsTable.tsx
+++ /dev/null
@@ -1,301 +0,0 @@
-import React, { useState, useMemo } from "react";
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getFilteredRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- SortingState,
- useReactTable,
- ColumnDef,
- FilterFn,
-} from "@tanstack/react-table";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
-import { UptimeMonitor, useMonitors } from "@/api/uptime/monitors";
-import { Skeleton } from "@/components/ui/skeleton";
-import { getTimezone } from "@/lib/store";
-import { Radio, ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
-import { StatusOrb } from "./StatusOrb";
-import { UptimeBar } from "./UptimeBar";
-import { Input } from "../../../../components/ui/input";
-import { Button } from "../../../../components/ui/button";
-import { Pagination } from "../../../../components/pagination";
-import { cn } from "@/lib/utils";
-import { DateTime } from "luxon";
-
-interface MonitorsTableProps {
- onMonitorClick?: (monitor: UptimeMonitor) => void;
-}
-
-// Define the fuzzy filter function
-const fuzzyFilter: FilterFn<UptimeMonitor> = (row, columnId, value, addMeta) => {
- const search = value.toLowerCase();
- const monitor = row.original;
-
- // Search in name (if it exists)
- if (monitor.name && monitor.name.toLowerCase().includes(search)) return true;
-
- // Search in URL/host
- if (monitor.monitorType === "http" && monitor.httpConfig?.url?.toLowerCase().includes(search)) return true;
- if (monitor.monitorType === "tcp" && monitor.tcpConfig?.host?.toLowerCase().includes(search)) return true;
-
- // Search in type
- if (monitor.monitorType.toLowerCase().includes(search)) return true;
-
- return false;
-};
-
-const formatLastPing = (lastCheckedAt?: string) => {
- if (!lastCheckedAt) return "-";
-
- const lastPing = DateTime.fromSQL(lastCheckedAt, {
- zone: "utc",
- }).setZone(getTimezone());
-
- const now = DateTime.now();
- const diffMs = now.toMillis() - lastPing.toMillis();
-
- const seconds = Math.floor(diffMs / 1000);
- const minutes = Math.floor(seconds / 60);
- const hours = Math.floor(minutes / 60);
- const days = Math.floor(hours / 24);
-
- if (days > 0) return `${days}d ago`;
- if (hours > 0) return `${hours}h ago`;
- if (minutes > 0) return `${minutes}m ago`;
- if (seconds > 0) return `${seconds}s ago`;
- return "just now";
-};
-
-const formatPercentage = (value?: number) => {
- if (value === undefined || value === null) return "-";
- return `${value.toFixed(1)}%`;
-};
-
-// Create column helper
-const columnHelper = createColumnHelper<UptimeMonitor>();
-
-// Sort header component
-const SortHeader = ({ column, children }: any) => {
- const isSorted = column.getIsSorted();
-
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}
- className="p-0 hover:bg-transparent"
- >
- {children}
- {isSorted ? (
- isSorted === "asc" ? (
- <ArrowUp className="ml-2 h-4 w-4" />
- ) : (
- <ArrowDown className="ml-2 h-4 w-4" />
- )
- ) : (
- <ArrowUpDown className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
-};
-
-export function MonitorsTable({ onMonitorClick }: MonitorsTableProps) {
- const { data: monitors = [], isLoading } = useMonitors();
- const [globalFilter, setGlobalFilter] = useState("");
- const [sorting, setSorting] = useState<SortingState>([]);
- const [pagination, setPagination] = useState({
- pageIndex: 0,
- pageSize: 10,
- });
-
- // Define columns
- const columns = useMemo(
- () => [
- columnHelper.display({
- id: "status",
- header: () => <Radio className="ml-2 w-4 h-4" />,
- cell: ({ row }) => (
- <div className="text-center">
- <StatusOrb status={row.original.status?.currentStatus || "unknown"} />
- </div>
- ),
- size: 48,
- }),
- columnHelper.accessor("name", {
- header: ({ column }) => <SortHeader column={column}>Monitor</SortHeader>,
- cell: ({ row }) => {
- const displayName =
- row.original.name ||
- (row.original.monitorType === "http"
- ? row.original.httpConfig?.url
- : `${row.original.tcpConfig?.host}:${row.original.tcpConfig?.port}`);
- const subtext = row.original.name
- ? row.original.monitorType === "http"
- ? row.original.httpConfig?.url
- : `${row.original.tcpConfig?.host}:${row.original.tcpConfig?.port}`
- : null;
-
- return (
- <div>
- <div className="font-medium">{displayName}</div>
- {subtext && <div className="text-xs text-neutral-500">{subtext}</div>}
- </div>
- );
- },
- }),
- columnHelper.accessor("monitorType", {
- header: ({ column }) => <SortHeader column={column}>Type</SortHeader>,
- cell: ({ getValue }) => {
- const type = getValue();
- return (
- <span
- className={cn(
- "inline-flex items-center px-2 py-1 text-xs font-medium rounded-full",
- type === "http" ? "bg-blue-500/20 text-blue-400" : "bg-purple-500/20 text-purple-400"
- )}
- >
- {type.toUpperCase()}
- </span>
- );
- },
- size: 96,
- }),
- columnHelper.display({
- id: "uptime-bar",
- header: "Last 7 Days",
- cell: ({ row }) => <UptimeBar monitorId={row.original.id} />,
- size: 192,
- }),
- columnHelper.accessor(row => row.status?.lastCheckedAt, {
- id: "lastPing",
- header: ({ column }) => <SortHeader column={column}>Last Ping</SortHeader>,
- cell: ({ getValue }) => <span className="text-neutral-300">{formatLastPing(getValue())}</span>,
- size: 112,
- }),
- columnHelper.accessor(row => row.status?.uptimePercentage7d, {
- id: "uptimePercentage",
- header: ({ column }) => (
- <SortHeader column={column}>
- <span className="whitespace-nowrap">Uptime %</span>
- </SortHeader>
- ),
- cell: ({ getValue }) => <div className="text-right text-neutral-300">{formatPercentage(getValue())}</div>,
- size: 80,
- }),
- ],
- []
- );
-
- // Create table instance
- const table = useReactTable({
- data: monitors,
- columns,
- state: {
- globalFilter,
- sorting,
- pagination,
- },
- onGlobalFilterChange: setGlobalFilter,
- onSortingChange: setSorting,
- onPaginationChange: setPagination,
- getCoreRowModel: getCoreRowModel(),
- getFilteredRowModel: getFilteredRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- globalFilterFn: fuzzyFilter,
- });
-
- return (
- <div className="space-y-4">
- <Input
- placeholder="Search monitors by name, URL, or type..."
- value={globalFilter}
- onChange={e => setGlobalFilter(e.target.value)}
- className="max-w-sm bg-neutral-900"
- />
- <div className="rounded-lg border border-neutral-800">
- <Table>
- <TableHeader>
- {table.getHeaderGroups().map(headerGroup => (
- <TableRow key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <TableHead
- key={header.id}
- style={{
- width: header.getSize() === 150 ? undefined : header.getSize(),
- }}
- >
- {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
- </TableHead>
- ))}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {isLoading ? (
- Array.from({ length: 5 }).map((_, i) => (
- <TableRow key={`skeleton-${i}`}>
- <TableCell>
- <Skeleton className="h-4 w-4 rounded-full mx-auto" />
- </TableCell>
- <TableCell>
- <div className="space-y-1">
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-3 w-48" />
- </div>
- </TableCell>
- <TableCell>
- <Skeleton className="h-6 w-12" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-20" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-12 ml-auto" />
- </TableCell>
- </TableRow>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
- <TableRow>
- <TableCell colSpan={columns.length} className="text-center text-neutral-500 py-8">
- {globalFilter ? "No monitors match your search" : "No monitors configured"}
- </TableCell>
- </TableRow>
- ) : (
- table.getRowModel().rows.map(row => (
- <TableRow
- key={row.id}
- className="cursor-pointer hover:bg-neutral-900/50"
- onClick={() => onMonitorClick?.(row.original)}
- >
- {row.getVisibleCells().map(cell => (
- <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
- ))}
- </TableRow>
- ))
- )}
- </TableBody>
- </Table>
- </div>
-
- {/* Pagination */}
- {!isLoading && monitors.length > 0 && (
- <Pagination
- table={table}
- data={{
- items: table.getFilteredRowModel().rows.map(row => row.original),
- total: table.getFilteredRowModel().rows.length,
- }}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName="monitors"
- />
- )}
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx b/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx
deleted file mode 100644
index 12f61a4df..000000000
--- a/client/src/app/uptime/monitors/components/Sidebar/MobileSidebar.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-"use client";
-
-import { UptimeSidebar } from "./UptimeSidebar";
-
-import { Menu } from "lucide-react";
-import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
-import { AppSidebar } from "../../../../../components/AppSidebar";
-import { Button } from "../../../../../components/ui/button";
-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "../../../../../components/ui/sheet";
-
-export function MobileSidebar() {
- return (
- <div className="md:hidden flex items-center gap-2">
- <Sheet>
- <SheetTrigger asChild>
- <Button size="icon" variant="outline">
- <Menu />
- </Button>
- </SheetTrigger>
- <VisuallyHidden>
- <SheetHeader>
- <SheetTitle>Rybbit Sidebar</SheetTitle>
- </SheetHeader>
- </VisuallyHidden>
- <SheetContent side="left" className="p-0 w-[240px] flex gap-0" showClose={false}>
- <AppSidebar />
- <UptimeSidebar />
- </SheetContent>
- </Sheet>
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/Sidebar/UptimeSidebar.tsx b/client/src/app/uptime/monitors/components/Sidebar/UptimeSidebar.tsx
deleted file mode 100644
index a27d6ffff..000000000
--- a/client/src/app/uptime/monitors/components/Sidebar/UptimeSidebar.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-"use client";
-import { Activity, AlertCircle, Plug2, Globe } from "lucide-react";
-import { usePathname } from "next/navigation";
-import { Sidebar } from "../../../../../components/sidebar/Sidebar";
-
-export function UptimeSidebar() {
- const pathname = usePathname();
-
- return (
- <Sidebar.Root>
- <Sidebar.Title>Uptime</Sidebar.Title>
- <Sidebar.Items>
- <Sidebar.Item
- label="Monitors"
- active={pathname.startsWith("/uptime/monitors")}
- href={"/uptime/monitors"}
- icon={<Activity className="w-4 h-4" />}
- />
- <Sidebar.Item
- label="Incidents"
- active={pathname.startsWith("/uptime/incidents")}
- href={"/uptime/incidents"}
- icon={<AlertCircle className="w-4 h-4" />}
- />
- <Sidebar.Item
- label="Notifications"
- active={pathname.startsWith("/uptime/notifications")}
- href={"/uptime/notifications"}
- icon={<Plug2 className="w-4 h-4" />}
- />
- <Sidebar.Item
- label="Status Page"
- active={pathname.startsWith("/uptime/status-page")}
- href={"/uptime/status-page"}
- icon={<Globe className="w-4 h-4" />}
- />
- </Sidebar.Items>
- </Sidebar.Root>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/StatusOrb.tsx b/client/src/app/uptime/monitors/components/StatusOrb.tsx
deleted file mode 100644
index f666fe6e9..000000000
--- a/client/src/app/uptime/monitors/components/StatusOrb.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import React from "react";
-import { cn } from "@/lib/utils";
-
-interface StatusOrbProps {
- status: "up" | "down" | "unknown";
- className?: string;
- size?: "sm" | "md" | "lg";
- animated?: boolean;
-}
-
-export function StatusOrb({ status, className, size = "md", animated = true }: StatusOrbProps) {
- const sizeClasses = {
- sm: "w-2 h-2",
- md: "w-3 h-3",
- lg: "w-4 h-4",
- };
-
- const statusClasses = {
- up: "bg-green-400",
- down: "bg-red-500",
- unknown: "bg-gray-400 dark:bg-gray-600",
- };
-
- const pulseClasses = {
- up: "animate-pulse",
- down: "animate-pulse",
- unknown: "",
- };
-
- return (
- <div className={cn("relative inline-flex", className)}>
- <div
- className={cn(
- "rounded-full",
- sizeClasses[size],
- statusClasses[status],
- animated && status !== "unknown" && pulseClasses[status]
- )}
- />
- {animated && status !== "unknown" && (
- <div
- className={cn(
- "absolute inset-0 rounded-full opacity-75",
- sizeClasses[size],
- statusClasses[status],
- "animate-ping"
- )}
- />
- )}
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/UptimeBar.tsx b/client/src/app/uptime/monitors/components/UptimeBar.tsx
deleted file mode 100644
index 7f044f7cc..000000000
--- a/client/src/app/uptime/monitors/components/UptimeBar.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import React from "react";
-import { cn } from "@/lib/utils";
-import { getTimezone } from "@/lib/store";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { DateTime } from "luxon";
-import { useMonitorUptimeBuckets } from "@/api/uptime/monitors";
-
-interface UptimeBarProps {
- monitorId: number;
- className?: string;
-}
-
-export function UptimeBar({ monitorId, className }: UptimeBarProps) {
- const { data, isLoading } = useMonitorUptimeBuckets(monitorId, {
- bucket: "day",
- days: 7,
- });
-
- if (isLoading) {
- return (
- <div className={cn("flex gap-1 h-6", className)}>
- {Array.from({ length: 7 }).map((_, i) => (
- <div key={i} className="w-[10px] rounded-md bg-neutral-150 dark:bg-neutral-600 animate-pulse" />
- ))}
- </div>
- );
- }
-
- if (!data?.buckets) {
- return null;
- }
- // Process bucket data
- const days = data.buckets.map(bucket => {
- const date = DateTime.fromSQL(bucket.bucket_time).setZone(getTimezone());
- return {
- date: bucket.bucket_formatted,
- dateFormatted: date.toFormat("MMM dd"),
- dayOfWeek: date.toFormat("ccc"),
- totalChecks: bucket.total_checks,
- successCount: bucket.successful_checks,
- failureCount: bucket.failed_checks,
- timeoutCount: bucket.timeout_checks,
- uptimePercentage: bucket.uptime_percentage,
- };
- });
-
- return (
- <TooltipProvider>
- <div className={cn("flex gap-1 h-6", className)}>
- {days.map(day => {
- const totalChecks = day.totalChecks;
- const hasIssues = day.failureCount > 0 || day.timeoutCount > 0;
- const uptimePercentage = day.uptimePercentage.toFixed(1);
-
- let barColor = "bg-green-500";
- if (totalChecks === 0) {
- barColor = "bg-neutral-300 dark:bg-neutral-600";
- } else if (day.failureCount > 0 || day.timeoutCount > 0) {
- const issuePercentage = (day.failureCount + day.timeoutCount) / totalChecks;
- if (issuePercentage >= 0.5) barColor = "bg-red-500";
- else if (issuePercentage >= 0.1) barColor = "bg-orange-500";
- else barColor = "bg-yellow-500";
- }
- if (totalChecks === 0) {
- return (
- <div
- key={day.date}
- className={cn("w-[10px] rounded-md cursor-pointer transition-opacity hover:opacity-80", barColor)}
- />
- );
- }
-
- return (
- <Tooltip key={day.date}>
- <TooltipTrigger asChild>
- <div
- className={cn("w-[10px] rounded-md cursor-pointer transition-opacity hover:opacity-80", barColor)}
- />
- </TooltipTrigger>
- <TooltipContent>
- <div className="text-sm space-y-1">
- <div className="flex items-center gap-4">
- <div className="font-medium">{uptimePercentage}%</div>
- <div className="text-neutral-300">{day.dateFormatted}</div>
- </div>
- {totalChecks > 0 ? (
- <>
- <div className="text-xs text-neutral-300">
- <span className="text-green-400">{day.successCount}</span> /{" "}
- <span className="text-red-400">{day.failureCount}</span> /{" "}
- <span className="text-orange-400">{day.timeoutCount}</span>
- </div>
- </>
- ) : (
- <div className="text-xs text-neutral-300 mt-1">No data</div>
- )}
- </div>
- </TooltipContent>
- </Tooltip>
- );
- })}
- </div>
- </TooltipProvider>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx b/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx
deleted file mode 100644
index 892e9059a..000000000
--- a/client/src/app/uptime/monitors/components/UptimeBucketSelection.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-"use client";
-
-import React from "react";
-import { SelectItem, Select, SelectContent, SelectTrigger, SelectValue } from "@/components/ui/select";
-
-export type TimeBucket =
- | "minute"
- | "five_minutes"
- | "ten_minutes"
- | "fifteen_minutes"
- | "hour"
- | "day"
- | "week"
- | "month"
- | "year";
-
-interface UptimeBucketSelectionProps {
- timeRange: string;
- bucket: TimeBucket;
- onBucketChange: (bucket: TimeBucket) => void;
-}
-
-const getBucketOptions = (timeRange: string): TimeBucket[] => {
- switch (timeRange) {
- case "1h":
- return ["minute", "five_minutes", "fifteen_minutes", "hour"];
- case "6h":
- return ["minute", "five_minutes", "fifteen_minutes", "hour"];
- case "12h":
- return ["minute", "five_minutes", "fifteen_minutes", "hour"];
- case "24h":
- return ["minute", "five_minutes", "fifteen_minutes", "hour"];
- case "3d":
- return ["five_minutes", "fifteen_minutes", "hour"];
- case "7d":
- return ["fifteen_minutes", "hour", "day"];
- case "30d":
- return ["hour", "day", "week"];
- case "90d":
- return ["hour", "day", "week", "month"];
- case "180d":
- return ["hour", "day", "week", "month", "year"];
- case "365d":
- return ["hour", "day", "week", "month", "year"];
- case "all":
- return ["day", "week", "month", "year"];
- default:
- return ["hour"];
- }
-};
-
-const bucketLabels: Record<TimeBucket, string> = {
- minute: "Minute",
- five_minutes: "5 Minutes",
- ten_minutes: "10 Minutes",
- fifteen_minutes: "15 Minutes",
- hour: "Hour",
- day: "Day",
- week: "Week",
- month: "Month",
- year: "Year",
-};
-
-export function UptimeBucketSelection({ timeRange, bucket, onBucketChange }: UptimeBucketSelectionProps) {
- const availableBuckets = getBucketOptions(timeRange);
-
- // If current bucket is not available for the time range, select the first available one
- React.useEffect(() => {
- if (!availableBuckets.includes(bucket)) {
- onBucketChange(availableBuckets[0]);
- }
- }, [timeRange, bucket, availableBuckets, onBucketChange]);
-
- return (
- <Select value={bucket} onValueChange={value => onBucketChange(value as TimeBucket)}>
- <SelectTrigger className="w-[120px]" size="sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {availableBuckets.map(bucketOption => (
- <SelectItem key={bucketOption} value={bucketOption} size="sm">
- {bucketLabels[bucketOption]}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx b/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx
deleted file mode 100644
index 03264598e..000000000
--- a/client/src/app/uptime/monitors/components/dialog/AdvancedTab.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import React from "react";
-import { UseFormReturn } from "react-hook-form";
-import { Input } from "@/components/ui/input";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Switch } from "@/components/ui/switch";
-import { Button } from "@/components/ui/button";
-import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
-import { Plus, X } from "lucide-react";
-import { Textarea } from "@/components/ui/textarea";
-import { CreateMonitorFormData, UpdateMonitorFormData } from "../monitorSchemas";
-
-interface AdvancedTabProps {
- form: UseFormReturn<CreateMonitorFormData | UpdateMonitorFormData>;
- monitorType: "http" | "tcp";
-}
-
-export function AdvancedTab({ form, monitorType }: AdvancedTabProps) {
- return (
- <div className="space-y-4">
- {/* Monitor Name */}
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Monitor Name</FormLabel>
- <FormControl>
- <Input placeholder="My API Endpoint" {...field} value={field.value || ""} />
- </FormControl>
- <FormDescription>
- A friendly name for this monitor. If not specified, the URL or host will be used.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {monitorType === "tcp" ? (
- <div className="text-sm text-neutral-500 mt-4">No additional advanced options available for TCP monitors.</div>
- ) : (
- <>
- <FormField
- control={form.control}
- name="httpConfig.userAgent"
- render={({ field }) => (
- <FormItem>
- <FormLabel>User Agent</FormLabel>
- <FormControl>
- <Input placeholder="Custom User Agent" {...field} value={field.value || ""} />
- </FormControl>
- <FormDescription>Override the default user agent string</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="httpConfig.headers"
- render={({ field }) => {
- // Use local state to manage headers array
- const [localHeaders, setLocalHeaders] = React.useState<Array<{ key: string; value: string; id: string }>>(
- () => {
- if (!field.value) return [];
- return Object.entries(field.value).map(([key, value], index) => ({
- key,
- value: value as string,
- id: `header_${index}_${Date.now()}`,
- }));
- }
- );
-
- // Sync local state changes back to form field
- React.useEffect(() => {
- const headersObject = localHeaders
- .filter(h => h.key !== "") // Only include headers with keys
- .reduce((acc, { key, value }) => ({ ...acc, [key]: value }), {});
-
- field.onChange(Object.keys(headersObject).length > 0 ? headersObject : undefined);
- }, [localHeaders, field]);
-
- const updateHeader = (id: string, type: "key" | "value", newValue: string) => {
- setLocalHeaders(prev =>
- prev.map(header => (header.id === id ? { ...header, [type]: newValue } : header))
- );
- };
-
- const removeHeader = (id: string) => {
- setLocalHeaders(prev => prev.filter(header => header.id !== id));
- };
-
- const addHeader = () => {
- setLocalHeaders(prev => [
- ...prev,
- {
- key: "",
- value: "",
- id: `header_${Date.now()}`,
- },
- ]);
- };
-
- return (
- <FormItem>
- <div className="flex items-center justify-between mb-2">
- <FormLabel>Custom Headers</FormLabel>
- <Button type="button" variant="outline" size="sm" onClick={addHeader} className="h-8">
- <Plus className="h-4 w-4 mr-1" />
- Add header
- </Button>
- </div>
- <div className="space-y-2">
- {localHeaders.map(header => (
- <div key={header.id} className="flex gap-2 items-center">
- <Input
- placeholder="Header name"
- value={header.key}
- onChange={e => updateHeader(header.id, "key", e.target.value)}
- className="flex-1"
- />
- <Input
- placeholder="Header value"
- value={header.value}
- onChange={e => updateHeader(header.id, "value", e.target.value)}
- className="flex-1"
- />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => removeHeader(header.id)}
- className="px-2"
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- ))}
- {localHeaders.length === 0 && (
- <div className="text-sm text-neutral-500">No custom headers added</div>
- )}
- </div>
- <FormDescription>Additional headers to send with requests</FormDescription>
- <FormMessage />
- </FormItem>
- );
- }}
- />
-
- <FormField
- control={form.control}
- name="httpConfig.body"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Request Body</FormLabel>
- <FormControl>
- <Textarea
- placeholder='{"key": "value"}'
- {...field}
- value={field.value || ""}
- className="font-mono min-h-[100px]"
- style={{ fontSize: "12px" }}
- />
- </FormControl>
- <FormDescription>Request body for POST, PUT, PATCH methods. Usually JSON or form data.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="httpConfig.followRedirects"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <FormLabel>Follow Redirects</FormLabel>
- <FormDescription>Automatically follow HTTP redirects</FormDescription>
- </div>
- <FormControl>
- <Switch checked={field.value} onCheckedChange={field.onChange} />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="httpConfig.ipVersion"
- render={({ field }) => (
- <FormItem>
- <FormLabel>IP Version</FormLabel>
- <Select onValueChange={field.onChange} value={field.value} defaultValue={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="any">Any</SelectItem>
- <SelectItem value="ipv4">IPv4 Only</SelectItem>
- <SelectItem value="ipv6">IPv6 Only</SelectItem>
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- </>
- )}
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx b/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx
deleted file mode 100644
index c56ddc1e9..000000000
--- a/client/src/app/uptime/monitors/components/dialog/GeneralTab.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import React from "react";
-import { UseFormReturn } from "react-hook-form";
-import { Input } from "@/components/ui/input";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Switch } from "@/components/ui/switch";
-import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
-import { UptimeMonitor } from "@/api/uptime/monitors";
-import { CreateMonitorFormData, UpdateMonitorFormData } from "../monitorSchemas";
-
-interface GeneralTabProps {
- form: UseFormReturn<CreateMonitorFormData | UpdateMonitorFormData>;
- monitor?: UptimeMonitor;
- isEdit: boolean;
- monitorType: "http" | "tcp";
-}
-
-export const INTERVAL_OPTIONS = [
- { value: 30, label: "30 seconds" },
- { value: 60, label: "1 minute" },
- { value: 120, label: "2 minutes" },
- { value: 180, label: "3 minutes" },
- { value: 300, label: "5 minutes" },
- { value: 600, label: "10 minutes" },
- { value: 1800, label: "30 minutes" },
-];
-
-const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"] as const;
-
-export function GeneralTab({ form, monitor, isEdit, monitorType }: GeneralTabProps) {
- return (
- <div className="space-y-4">
- {/* Monitor Type */}
- {!isEdit ? (
- <FormField
- control={form.control}
- name="monitorType"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Monitor Type</FormLabel>
- <Select onValueChange={field.onChange} defaultValue={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="http">HTTP/HTTPS</SelectItem>
- <SelectItem value="tcp">TCP Port</SelectItem>
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- ) : (
- <div className="space-y-1">
- <FormLabel>Monitor Type</FormLabel>
- <div className="px-3 py-2 border border-neutral-800 rounded-md bg-neutral-900 text-neutral-400">
- {monitor?.monitorType === "http" ? "HTTP/HTTPS" : "TCP Port"}
- </div>
- </div>
- )}
-
- {/* HTTP Configuration */}
- {monitorType === "http" && (
- <>
- <FormField
- control={form.control}
- name="httpConfig.url"
- render={({ field }) => (
- <FormItem>
- <FormLabel>URL</FormLabel>
- <FormControl>
- <Input type="url" placeholder="https://api.example.com/health" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={form.control}
- name="httpConfig.method"
- render={({ field }) => (
- <FormItem>
- <FormLabel>HTTP Method</FormLabel>
- <Select onValueChange={field.onChange} value={field.value} defaultValue={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {HTTP_METHODS.map(method => (
- <SelectItem key={method} value={method}>
- {method}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="httpConfig.timeoutMs"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Timeout (ms)</FormLabel>
- <FormControl>
- <Input
- type="number"
- {...field}
- value={field.value || ""}
- onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </>
- )}
-
- {/* TCP Configuration */}
- {monitorType === "tcp" && (
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={form.control}
- name="tcpConfig.host"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Host</FormLabel>
- <FormControl>
- <Input placeholder="example.com" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="tcpConfig.port"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Port</FormLabel>
- <FormControl>
- <Input
- type="number"
- {...field}
- value={field.value || ""}
- onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- )}
-
- {/* Check Interval */}
- <FormField
- control={form.control}
- name="intervalSeconds"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Check Interval</FormLabel>
- <Select
- onValueChange={value => field.onChange(parseInt(value))}
- value={field.value?.toString()}
- defaultValue={field.value?.toString()}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {INTERVAL_OPTIONS.map(option => (
- <SelectItem key={option.value} value={option.value.toString()}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {/* Enabled Switch */}
- <FormField
- control={form.control}
- name="enabled"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <FormLabel>Enable Monitor</FormLabel>
- <FormDescription>
- {isEdit
- ? "Monitor will run at the configured interval when enabled"
- : "Start monitoring immediately after creation"}
- </FormDescription>
- </div>
- <FormControl>
- <Switch checked={field.value} onCheckedChange={field.onChange} />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx b/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx
deleted file mode 100644
index 22db7cebe..000000000
--- a/client/src/app/uptime/monitors/components/dialog/MonitorDialog.tsx
+++ /dev/null
@@ -1,281 +0,0 @@
-import React, { useEffect } from "react";
-import { useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import { useCreateMonitor, useUpdateMonitor, UptimeMonitor } from "@/api/uptime/monitors";
-import { toast } from "@/components/ui/sonner";
-import { Loader2 } from "lucide-react";
-import { createMonitorSchema, updateMonitorSchema } from "../monitorSchemas";
-import { Form } from "@/components/ui/form";
-import { authClient } from "../../../../../lib/auth";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/basic-tabs";
-import { GeneralTab } from "./GeneralTab";
-import { AdvancedTab } from "./AdvancedTab";
-import { RegionsTab } from "./RegionsTab";
-import { NotificationsTab } from "./NotificationsTab";
-import { IS_CLOUD } from "@/lib/const";
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../../../../../api/utils";
-
-interface MonitorDialogProps {
- monitor?: UptimeMonitor;
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}
-
-export function MonitorDialog({ monitor, open, onOpenChange }: MonitorDialogProps) {
- const { data: activeOrganization, isPending } = authClient.useActiveOrganization();
- const createMonitor = useCreateMonitor();
- const updateMonitor = useUpdateMonitor();
- const isEdit = !!monitor;
-
- // Fetch available regions
- const { data: regionsData } = useQuery({
- queryKey: ["uptime-regions"],
- queryFn: async () => {
- const response = await authedFetch<{
- regions: Array<{ code: string; name: string; isHealthy: boolean; isLocal: boolean }>;
- }>("/uptime/regions");
- return response.regions;
- },
- enabled: open && IS_CLOUD,
- });
-
- const form = useForm<any>({
- resolver: zodResolver(isEdit ? updateMonitorSchema : createMonitorSchema),
- defaultValues: isEdit
- ? {
- name: monitor.name,
- intervalSeconds: monitor.intervalSeconds,
- enabled: monitor.enabled,
- httpConfig: monitor.httpConfig
- ? {
- url: monitor.httpConfig.url,
- method: monitor.httpConfig.method as any,
- headers: monitor.httpConfig.headers,
- body: monitor.httpConfig.body,
- auth: monitor.httpConfig.auth,
- followRedirects: monitor.httpConfig.followRedirects ?? true,
- timeoutMs: monitor.httpConfig.timeoutMs ?? 30000,
- ipVersion: monitor.httpConfig.ipVersion ?? "any",
- userAgent: monitor.httpConfig.userAgent,
- }
- : undefined,
- tcpConfig: monitor.tcpConfig
- ? {
- host: monitor.tcpConfig.host,
- port: monitor.tcpConfig.port,
- timeoutMs: monitor.tcpConfig.timeoutMs ?? 30000,
- }
- : undefined,
- validationRules: monitor.validationRules || [],
- monitoringType: monitor.monitoringType || "local",
- selectedRegions: monitor.selectedRegions || ["local"],
- }
- : {
- organizationId: activeOrganization?.id || "",
- name: "", // Optional - will be empty by default
- monitorType: "http" as const,
- intervalSeconds: 180,
- enabled: true,
- httpConfig: {
- url: "",
- method: "GET" as const,
- followRedirects: true,
- timeoutMs: 30000,
- ipVersion: "any" as const,
- },
- validationRules: [],
- monitoringType: IS_CLOUD ? "global" : "local",
- selectedRegions: IS_CLOUD ? [] : ["local"], // Empty array for cloud, will be populated in RegionsTab
- },
- });
-
- const monitorType = isEdit ? monitor.monitorType : form.watch("monitorType");
-
- const onSubmit = async (data: any) => {
- try {
- if (isEdit) {
- await updateMonitor.mutateAsync({
- monitorId: monitor.id,
- data,
- });
- toast.success("Monitor updated successfully");
- } else {
- await createMonitor.mutateAsync(data);
- toast.success("Monitor created successfully");
- }
- onOpenChange(false);
- form.reset();
- } catch (error: any) {
- console.error("Submit error:", error);
- toast.error(error.response?.data?.error || `Failed to ${isEdit ? "update" : "create"} monitor`);
- }
- };
-
- // Set organization ID when active organization changes (create mode only)
- useEffect(() => {
- if (!isEdit && activeOrganization?.id) {
- form.setValue("organizationId", activeOrganization.id);
- }
- }, [activeOrganization, form, isEdit]);
-
- // Initialize regions for new monitors in cloud mode
- useEffect(() => {
- if (open && !isEdit && IS_CLOUD && regionsData) {
- const globalRegions = regionsData.filter(r => !r.isLocal && r.isHealthy);
- if (globalRegions.length > 0) {
- const currentRegions = form.getValues("selectedRegions");
- // Only set if empty or has default "local" value
- if (
- !currentRegions ||
- currentRegions.length === 0 ||
- (currentRegions.length === 1 && currentRegions[0] === "local")
- ) {
- form.setValue(
- "selectedRegions",
- globalRegions.map(r => r.code)
- );
- }
- }
- }
- }, [open, isEdit, IS_CLOUD, regionsData, form]);
-
- // Reset form when dialog closes or monitor changes
- useEffect(() => {
- if (!open) {
- form.reset();
- } else if (isEdit && monitor) {
- form.reset({
- name: monitor.name,
- intervalSeconds: monitor.intervalSeconds,
- enabled: monitor.enabled,
- httpConfig: monitor.httpConfig
- ? {
- url: monitor.httpConfig.url,
- method: monitor.httpConfig.method as any,
- headers: monitor.httpConfig.headers,
- body: monitor.httpConfig.body,
- auth: monitor.httpConfig.auth,
- followRedirects: monitor.httpConfig.followRedirects ?? true,
- timeoutMs: monitor.httpConfig.timeoutMs ?? 30000,
- ipVersion: monitor.httpConfig.ipVersion ?? "any",
- userAgent: monitor.httpConfig.userAgent,
- }
- : undefined,
- tcpConfig: monitor.tcpConfig
- ? {
- host: monitor.tcpConfig.host,
- port: monitor.tcpConfig.port,
- timeoutMs: monitor.tcpConfig.timeoutMs ?? 30000,
- }
- : undefined,
- validationRules: monitor.validationRules || [],
- monitoringType: monitor.monitoringType || "local",
- selectedRegions: monitor.selectedRegions || ["local"],
- });
- }
- }, [monitor, open, form, isEdit]);
-
- // Update form when monitor type changes (create mode only)
- useEffect(() => {
- if (!isEdit && form.watch) {
- const subscription = form.watch((value, { name }) => {
- if (name === "monitorType") {
- if (value.monitorType === "tcp") {
- form.setValue("httpConfig", undefined as any);
- form.setValue("tcpConfig", {
- host: "",
- port: 80,
- timeoutMs: 30000,
- });
- } else {
- form.setValue("tcpConfig", undefined as any);
- form.setValue("httpConfig", {
- url: "",
- method: "GET" as const,
- followRedirects: true,
- timeoutMs: 30000,
- ipVersion: "any" as const,
- });
- }
- }
- });
- return () => subscription.unsubscribe();
- }
- }, [form, isEdit]);
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
- <Form {...form}>
- <form>
- <DialogHeader>
- <DialogTitle>{isEdit ? "Edit" : "Create New"} Monitor</DialogTitle>
- <DialogDescription>
- {isEdit
- ? "Update the configuration for this monitor."
- : "Set up a new uptime monitor to track the availability of your endpoints."}
- </DialogDescription>
- </DialogHeader>
-
- <Tabs defaultValue="general" className="mt-4">
- <TabsList className="">
- <TabsTrigger value="general">General</TabsTrigger>
- <TabsTrigger value="advanced">Advanced</TabsTrigger>
- <TabsTrigger value="regions">Regions</TabsTrigger>
- <TabsTrigger value="notifications">Notifications</TabsTrigger>
- </TabsList>
-
- <TabsContent value="general" className="space-y-4 mt-4">
- <GeneralTab form={form} monitor={monitor} isEdit={isEdit} monitorType={monitorType} />
- </TabsContent>
-
- <TabsContent value="advanced" className="space-y-4 mt-4">
- <AdvancedTab form={form} monitorType={monitorType} />
- </TabsContent>
-
- <TabsContent value="regions" className="space-y-4 mt-4">
- <RegionsTab />
- </TabsContent>
-
- <TabsContent value="notifications" className="space-y-4 mt-4">
- <NotificationsTab />
- </TabsContent>
- </Tabs>
-
- <DialogFooter className="mt-6">
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={createMonitor.isPending || updateMonitor.isPending}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- variant="success"
- disabled={
- (isEdit ? updateMonitor.isPending : createMonitor.isPending) ||
- (!isEdit && (isPending || !activeOrganization))
- }
- >
- {(createMonitor.isPending || updateMonitor.isPending) && <Loader2 className="h-4 w-4 animate-spin" />}
- {isEdit ? "Update" : "Create"} Monitor
- </Button>
- </DialogFooter>
- </form>
- </Form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx b/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx
deleted file mode 100644
index 47a5fbe60..000000000
--- a/client/src/app/uptime/monitors/components/dialog/NotificationsTab.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import React from "react";
-
-export function NotificationsTab() {
- return <div className="text-neutral-500 text-sm">Notification settings will be available in a future update.</div>;
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx b/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx
deleted file mode 100644
index 882c1146b..000000000
--- a/client/src/app/uptime/monitors/components/dialog/RegionsTab.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-import React, { useEffect } from "react";
-import { useFormContext } from "react-hook-form";
-import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
-import { Alert, AlertDescription } from "@/components/ui/alert";
-import { Globe, Server, Info, Crown } from "lucide-react";
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../../../../../api/utils";
-import { Skeleton } from "@/components/ui/skeleton";
-import { CountryFlag } from "@/app/[site]/components/shared/icons/CountryFlag";
-import { IS_CLOUD } from "@/lib/const";
-import { cn } from "@/lib/utils";
-import { Checkbox } from "@/components/ui/checkbox";
-
-interface Region {
- code: string;
- name: string;
- isHealthy: boolean;
- lastHealthCheck: string | null;
- isLocal: boolean;
-}
-
-export function RegionsTab() {
- const form = useFormContext();
- const monitoringType = IS_CLOUD ? "global" : "local";
- const selectedRegions = form.watch("selectedRegions") || [];
-
- const { data: regionsData, isLoading } = useQuery({
- queryKey: ["uptime-regions"],
- queryFn: async () => {
- const response = await authedFetch<{ regions: Region[] }>("/uptime/regions");
- return response.regions;
- },
- });
-
- const regions = regionsData || [];
- const globalRegions = regions.filter((r: Region) => !r.isLocal);
-
- // Set monitoring type on mount
- useEffect(() => {
- form.setValue("monitoringType", monitoringType);
-
- // For local monitoring, ensure "local" is selected
- if (!IS_CLOUD) {
- form.setValue("selectedRegions", ["local"]);
- }
- }, [monitoringType, form, IS_CLOUD]);
-
- if (isLoading) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-8 w-full" />
- <Skeleton className="h-8 w-full" />
- <Skeleton className="h-8 w-full" />
- </div>
- );
- }
-
- // Map region codes to country codes for flags
- const regionToCountry: Record<string, string> = {
- "us-east": "US",
- "us-west": "US",
- eu: "EU",
- asia: "SG",
- };
-
- return (
- <div className="space-y-6">
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h3 className="text-sm font-medium flex items-center gap-2">
- {IS_CLOUD ? (
- <>
- <Globe className="h-4 w-4" /> Global Monitoring
- </>
- ) : (
- <>
- <Server className="h-4 w-4" /> Local Monitoring
- </>
- )}
- </h3>
- <p className="text-sm text-muted-foreground">
- {IS_CLOUD ? "Monitor from multiple regions worldwide" : "Monitor from your main server location only"}
- </p>
- </div>
- </div>
- </div>
-
- {IS_CLOUD ? (
- <>
- <FormField
- control={form.control}
- name="selectedRegions"
- render={() => (
- <FormItem>
- {/* <FormLabel>Select Regions</FormLabel>
- <FormDescription>
- Choose which regions to monitor from. More regions provide better coverage.
- </FormDescription> */}
- <div className="space-y-4 mt-4">
- {globalRegions.map((region: Region) => (
- <FormField
- key={region.code}
- control={form.control}
- name="selectedRegions"
- render={({ field }) => {
- const isSelected = field.value?.includes(region.code);
- const isDisabled = !region.isHealthy;
-
- return (
- <FormItem>
- <div className="flex items-center space-x-3">
- <FormControl>
- <Checkbox
- checked={isSelected}
- onCheckedChange={checked => {
- if (!isDisabled) {
- let newValue: string[];
- if (checked) {
- newValue = [...(field.value || []), region.code];
- } else {
- newValue = field.value?.filter((value: string) => value !== region.code) || [];
- // Ensure at least one region is selected
- if (newValue.length === 0) {
- return; // Don't allow unchecking the last region
- }
- }
- field.onChange(newValue);
- }
- }}
- disabled={isDisabled}
- className="data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500 dark:data-[state=checked]:bg-emerald-500"
- />
- </FormControl>
- <div className="flex items-center gap-2 flex-1">
- {regionToCountry[region.code] && (
- <CountryFlag country={regionToCountry[region.code]} className="w-5 h-3.5" />
- )}
- <label
- htmlFor={region.code}
- className={cn(
- "text-sm font-medium cursor-pointer",
- isDisabled && "opacity-50 cursor-not-allowed"
- )}
- >
- {region.name}
- </label>
- {!region.isHealthy && <span className="ml-auto text-xs text-red-500">Offline</span>}
- </div>
- </div>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {selectedRegions.length === 0 && (
- <Alert variant="destructive">
- <Info className="h-4 w-4" />
- <AlertDescription>Please select at least one region for global monitoring.</AlertDescription>
- </Alert>
- )}
-
- {selectedRegions.length === 1 && (
- <Alert>
- <Info className="h-4 w-4" />
- <AlertDescription>At least one region must remain selected.</AlertDescription>
- </Alert>
- )}
- </>
- ) : (
- <Alert>
- <Crown className="h-4 w-4" />
- <AlertDescription>
- Upgrade to Cloud or Enterprise tier to enable multi-region monitoring and get better uptime insights from
- multiple geographic locations.
- </AlertDescription>
- </Alert>
- )}
- </div>
- );
-}
diff --git a/client/src/app/uptime/monitors/components/dialog/index.ts b/client/src/app/uptime/monitors/components/dialog/index.ts
deleted file mode 100644
index c99b898a9..000000000
--- a/client/src/app/uptime/monitors/components/dialog/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { MonitorDialog } from "./MonitorDialog";
diff --git a/client/src/app/uptime/monitors/components/monitorSchemas.ts b/client/src/app/uptime/monitors/components/monitorSchemas.ts
deleted file mode 100644
index c2c929411..000000000
--- a/client/src/app/uptime/monitors/components/monitorSchemas.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-import { z } from "zod";
-
-// HTTP method enum
-const httpMethodSchema = z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]);
-
-// Auth type enum
-const authTypeSchema = z.enum(["none", "basic", "bearer", "api_key", "custom_header"]);
-
-// IP version enum
-const ipVersionSchema = z.enum(["any", "ipv4", "ipv6"]);
-
-// Auth credentials schema
-const authCredentialsSchema = z.object({
- username: z.string().optional(),
- password: z.string().optional(),
- token: z.string().optional(),
- headerName: z.string().optional(),
- headerValue: z.string().optional(),
-});
-
-// Auth schema
-const authSchema = z.object({
- type: authTypeSchema,
- credentials: authCredentialsSchema.optional(),
-});
-
-// HTTP config schema
-const httpConfigSchema = z.object({
- url: z.string().url("Please enter a valid URL"),
- method: httpMethodSchema,
- headers: z.record(z.string()).optional(),
- body: z.string().optional(),
- auth: authSchema.optional(),
- followRedirects: z.boolean(),
- timeoutMs: z.number().int().min(1000).max(300000),
- ipVersion: ipVersionSchema,
- userAgent: z.string().max(256).optional(),
-});
-
-// TCP config schema
-const tcpConfigSchema = z.object({
- host: z.string().min(1, "Host is required"),
- port: z.number().int().min(1, "Invalid port").max(65535, "Port must be between 1 and 65535"),
- timeoutMs: z.number().int().min(1000).max(300000),
-});
-
-// Partial schemas for updates
-const partialHttpConfigSchema = z.object({
- url: z.string().url("Please enter a valid URL").optional(),
- method: httpMethodSchema.optional(),
- headers: z.record(z.string()).optional(),
- body: z.string().optional(),
- auth: authSchema.optional(),
- followRedirects: z.boolean().optional(),
- timeoutMs: z.number().int().min(1000).max(300000).optional(),
- ipVersion: ipVersionSchema.optional(),
- userAgent: z.string().max(256).optional(),
-});
-
-const partialTcpConfigSchema = z.object({
- host: z.string().min(1, "Host is required").optional(),
- port: z.number().int().min(1, "Invalid port").max(65535, "Port must be between 1 and 65535").optional(),
- timeoutMs: z.number().int().min(1000).max(300000).optional(),
-});
-
-// Create monitor schema
-export const createMonitorSchema = z
- .object({
- organizationId: z.string().min(1, "Organization is required"),
- name: z.string().max(256).optional(), // Made optional
- monitorType: z.enum(["http", "tcp"]),
- intervalSeconds: z.number().int().min(30).max(86400),
- enabled: z.boolean(),
- httpConfig: httpConfigSchema.optional(),
- tcpConfig: tcpConfigSchema.optional(),
- validationRules: z.array(z.any()).optional(),
- monitoringType: z.enum(["local", "global"]).optional(),
- selectedRegions: z.array(z.string()).optional(),
- })
- .refine(
- data => {
- if (data.monitorType === "http") {
- return data.httpConfig !== undefined && data.httpConfig.url !== "";
- }
- if (data.monitorType === "tcp") {
- return data.tcpConfig !== undefined && data.tcpConfig.host !== "";
- }
- return false;
- },
- {
- message: "Monitor type specific configuration is required",
- }
- )
- .refine(
- data => {
- if (data.monitoringType === "global") {
- return data.selectedRegions && data.selectedRegions.length > 0;
- }
- return true;
- },
- {
- message: "At least one region must be selected for global monitoring",
- }
- );
-
-// Update monitor schema (all fields optional except what's being updated)
-export const updateMonitorSchema = z.object({
- name: z.string().max(256).optional(), // Allow empty string for removing name
- intervalSeconds: z.number().int().min(30).max(86400).optional(),
- enabled: z.boolean().optional(),
- httpConfig: partialHttpConfigSchema.optional(),
- tcpConfig: partialTcpConfigSchema.optional(),
- validationRules: z.array(z.any()).optional(),
- monitoringType: z.enum(["local", "global"]).optional(),
- selectedRegions: z.array(z.string()).optional(),
-});
-
-// Type exports
-export type CreateMonitorFormData = z.infer<typeof createMonitorSchema>;
-export type UpdateMonitorFormData = z.infer<typeof updateMonitorSchema>;
diff --git a/client/src/app/uptime/monitors/components/uptimeStore.ts b/client/src/app/uptime/monitors/components/uptimeStore.ts
deleted file mode 100644
index b158dbf8e..000000000
--- a/client/src/app/uptime/monitors/components/uptimeStore.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { create } from "zustand";
-import { TimeBucket } from "./UptimeBucketSelection";
-
-export const TIME_RANGES = [
- { value: "1h", label: "1H" },
- { value: "6h", label: "6H" },
- { value: "12h", label: "12H" },
- { value: "24h", label: "24H" },
- { value: "3d", label: "3D" },
- { value: "7d", label: "7D" },
- { value: "14d", label: "14D" },
- { value: "30d", label: "30D" },
- { value: "60d", label: "60D" },
- { value: "90d", label: "90D" },
- { value: "180d", label: "180D" },
- { value: "365d", label: "365D" },
- // { value: "all", label: "All Time" },
-] as const;
-
-export type TimeRange = (typeof TIME_RANGES)[number]["value"];
-
-export const useUptimeStore = create<{
- timeRange: TimeRange;
- setTimeRange: (timeRange: (typeof TIME_RANGES)[number]["value"]) => void;
- bucket: TimeBucket;
- setBucket: (bucket: TimeBucket) => void;
- selectedRegion?: string;
- setSelectedRegion: (region?: string) => void;
-}>(set => ({
- timeRange: "24h",
- setTimeRange: timeRange => set({ timeRange }),
- bucket: "minute",
- setBucket: bucket => set({ bucket }),
- selectedRegion: undefined,
- setSelectedRegion: region => set({ selectedRegion: region }),
-}));
diff --git a/client/src/app/uptime/monitors/components/utils.ts b/client/src/app/uptime/monitors/components/utils.ts
deleted file mode 100644
index 8de627916..000000000
--- a/client/src/app/uptime/monitors/components/utils.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { TimeRange } from "./uptimeStore";
-
-export const getHoursFromTimeRange = (timeRange: TimeRange) => {
- switch (timeRange) {
- case "1h":
- return 1;
- case "6h":
- return 6;
- case "12h":
- return 12;
- case "24h":
- return 24;
- case "3d":
- return 72;
- case "7d":
- return 168;
- case "14d":
- return 336;
- case "30d":
- return 720;
- case "60d":
- return 1440;
- case "90d":
- return 2160;
- case "180d":
- return 4320;
- case "365d":
- return 8760;
- default:
- return 24;
- }
-};
diff --git a/client/src/app/uptime/monitors/const.ts b/client/src/app/uptime/monitors/const.ts
deleted file mode 100644
index e4e6bdc5c..000000000
--- a/client/src/app/uptime/monitors/const.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const REGIONS = [
- { code: "all", name: "All Regions", countryCode: null },
- { code: "us-east", name: "US East", countryCode: "US" },
- { code: "us-west", name: "US West", countryCode: "US" },
- { code: "eu", name: "Europe", countryCode: "EU" },
- { code: "asia", name: "Asia", countryCode: "SG" }, // Singapore flag for Asia
-];
diff --git a/client/src/app/uptime/monitors/page.tsx b/client/src/app/uptime/monitors/page.tsx
deleted file mode 100644
index 448c66612..000000000
--- a/client/src/app/uptime/monitors/page.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-"use client";
-
-import { Button } from "@/components/ui/button";
-import { Plus } from "lucide-react";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { MonitorDialog } from "./components/dialog";
-import { MonitorsTable } from "./components/MonitorsTable";
-
-export default function UptimePage() {
- const router = useRouter();
- const [showCreateDialog, setShowCreateDialog] = useState(false);
-
- const handleMonitorClick = (monitor: any) => {
- router.push(`/uptime/monitors/${monitor.id}`);
- };
-
- return (
- <>
- <div className="flex items-center justify-between mb-6">
- <div>
- <h1 className="text-2xl font-semibold">Uptime Monitoring</h1>
- <p className="text-sm text-neutral-500 mt-1">Monitor the availability and performance of your endpoints</p>
- </div>
- <div className="flex items-center gap-2">
- <Button size="sm" className="flex items-center gap-2" onClick={() => setShowCreateDialog(true)}>
- <Plus className="h-4 w-4" />
- Add Monitor
- </Button>
- </div>
- </div>
-
- <MonitorsTable onMonitorClick={handleMonitorClick} />
-
- <MonitorDialog open={showCreateDialog} onOpenChange={setShowCreateDialog} />
- </>
- );
-}
diff --git a/client/src/app/uptime/notifications/components/NotificationDialog.tsx b/client/src/app/uptime/notifications/components/NotificationDialog.tsx
deleted file mode 100644
index cf7626b40..000000000
--- a/client/src/app/uptime/notifications/components/NotificationDialog.tsx
+++ /dev/null
@@ -1,297 +0,0 @@
-"use client";
-
-import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { toast } from "@/components/ui/sonner";
-import { useNotificationsStore } from "../notificationsStore";
-import { NotificationChannel, useCreateChannel, useUpdateChannel } from "@/api/uptime/notifications";
-import { CHANNEL_CONFIG } from "../constants";
-import { useForm } from "react-hook-form";
-import { useEffect, useState } from "react";
-import * as React from "react";
-import { useMonitors } from "@/api/uptime/monitors";
-import { MultiSelect } from "@/components/ui/multi-select";
-
-type FormData = {
- name: string;
- email?: string;
- webhookUrl?: string;
- slackWebhookUrl?: string;
- slackChannel?: string;
- phoneNumber?: string;
-};
-
-export function NotificationDialog() {
- const createChannel = useCreateChannel();
- const updateChannel = useUpdateChannel();
- const {
- isDialogOpen,
- selectedType,
- editingChannel,
- closeDialog,
- resetForm: resetStoreForm,
- } = useNotificationsStore();
- const { data: monitorsData, isLoading: monitorsLoading } = useMonitors({ enabled: true });
- const [selectedMonitorIds, setSelectedMonitorIds] = useState<string[]>([]);
-
- const {
- register,
- handleSubmit,
- formState: { errors, isValid },
- reset,
- watch,
- } = useForm<FormData>({
- mode: "onChange",
- defaultValues: {
- name: "",
- email: "",
- webhookUrl: "",
- slackWebhookUrl: "",
- slackChannel: "",
- phoneNumber: "",
- },
- });
-
- // Reset form when dialog closes or populate with editing data
- useEffect(() => {
- if (!isDialogOpen) {
- reset();
- setSelectedMonitorIds([]);
- } else if (editingChannel) {
- // Populate form with existing channel data
- reset({
- name: editingChannel.name,
- email: editingChannel.config?.email || "",
- webhookUrl: editingChannel.config?.webhookUrl || "",
- slackWebhookUrl: editingChannel.config?.slackWebhookUrl || "",
- slackChannel: editingChannel.config?.slackChannel || "",
- phoneNumber: editingChannel.config?.phoneNumber || "",
- });
- setSelectedMonitorIds(editingChannel.monitorIds?.map(id => id.toString()) || []);
- }
- }, [isDialogOpen, editingChannel, reset]);
-
- const monitorOptions = React.useMemo(() => {
- if (!monitorsData) return [];
- return monitorsData.map(monitor => ({
- value: monitor.id.toString(),
- label:
- monitor.name ||
- (monitor.monitorType === "http"
- ? monitor.httpConfig?.url || "HTTP Monitor"
- : `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}` || "TCP Monitor"),
- }));
- }, [monitorsData]);
-
- const onSubmit = async (data: FormData) => {
- if (!selectedType) return;
- const config: Partial<NotificationChannel["config"]> = {};
- if (selectedType === "email" && data.email) config.email = data.email;
- if (selectedType === "discord" && data.webhookUrl) config.webhookUrl = data.webhookUrl;
- if (selectedType === "slack") {
- if (data.slackWebhookUrl) config.slackWebhookUrl = data.slackWebhookUrl;
- if (data.slackChannel) config.slackChannel = data.slackChannel;
- }
- if (selectedType === "sms" && data.phoneNumber) config.phoneNumber = data.phoneNumber;
-
- try {
- const monitorIds = selectedMonitorIds.length > 0 ? selectedMonitorIds.map(id => parseInt(id, 10)) : null;
-
- if (editingChannel) {
- await updateChannel.mutateAsync({
- id: editingChannel.id,
- data: {
- name: data.name,
- config,
- monitorIds,
- },
- });
- toast.success("Notification channel updated");
- } else {
- await createChannel.mutateAsync({
- type: selectedType,
- name: data.name,
- config,
- monitorIds,
- });
- toast.success("Notification channel created");
- }
- closeDialog();
- resetStoreForm();
- reset();
- setSelectedMonitorIds([]);
- } catch (error) {
- toast.error(editingChannel ? "Failed to update channel" : "Failed to create channel");
- }
- };
-
- // Determine if form is valid based on selected channel type
- const isFormValid = () => {
- const values = watch();
- if (!values.name?.trim()) return false;
-
- switch (selectedType) {
- case "email":
- return !!values.email?.trim();
- case "discord":
- return !!values.webhookUrl?.trim();
- case "slack":
- return !!values.slackWebhookUrl?.trim();
- case "sms":
- return !!values.phoneNumber?.trim();
- default:
- return false;
- }
- };
-
- const selectedConfig = selectedType ? CHANNEL_CONFIG[selectedType] : null;
- const Icon = selectedConfig ? selectedConfig.icon : null;
-
- return (
- <Dialog open={isDialogOpen} onOpenChange={closeDialog}>
- <DialogContent className="max-w-lg">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-3">
- {Icon && <Icon />}
- {editingChannel ? "Edit" : "Add"} {selectedConfig && selectedConfig.title} Channel
- </DialogTitle>
- </DialogHeader>
- <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
- <div>
- <Label htmlFor="name">Channel Name</Label>
- <Input
- id="name"
- placeholder="e.g., Team Alerts"
- {...register("name", {
- required: "Channel name is required",
- minLength: { value: 1, message: "Channel name is required" },
- })}
- />
- {errors.name && <p className="text-sm text-red-500 mt-1">{errors.name.message}</p>}
- </div>
-
- {selectedType === "email" && (
- <div>
- <Label htmlFor="email">Email Address</Label>
- <Input
- id="email"
- type="email"
- placeholder="[email protected]"
- {...register("email", {
- required: "Email address is required",
- pattern: {
- value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
- message: "Invalid email address",
- },
- })}
- />
- {errors.email && <p className="text-sm text-red-500 mt-1">{errors.email.message}</p>}
- </div>
- )}
-
- {selectedType === "discord" && (
- <div>
- <Label htmlFor="webhookUrl">Discord Webhook URL</Label>
- <Input
- id="webhookUrl"
- placeholder="https://discord.com/api/webhooks/..."
- {...register("webhookUrl", {
- required: "Discord webhook URL is required",
- pattern: {
- value: /^https:\/\/discord\.com\/api\/webhooks\/.+/,
- message: "Invalid Discord webhook URL",
- },
- })}
- />
- <p className="text-xs text-neutral-500 mt-1">Create a webhook in your Discord server settings</p>
- {errors.webhookUrl && <p className="text-sm text-red-500 mt-1">{errors.webhookUrl.message}</p>}
- </div>
- )}
-
- {selectedType === "slack" && (
- <>
- <div>
- <Label htmlFor="slackWebhookUrl">Slack Webhook URL</Label>
- <Input
- id="slackWebhookUrl"
- placeholder="https://hooks.slack.com/services/..."
- {...register("slackWebhookUrl", {
- required: "Slack webhook URL is required",
- pattern: {
- value: /^https:\/\/hooks\.slack\.com\/(services|workflows)\/.+/,
- message: "Invalid Slack webhook URL",
- },
- })}
- />
- {errors.slackWebhookUrl && (
- <p className="text-sm text-red-500 mt-1">{errors.slackWebhookUrl.message}</p>
- )}
- </div>
- <div>
- <Label htmlFor="slackChannel">Channel (optional)</Label>
- <Input id="slackChannel" placeholder="#alerts" {...register("slackChannel")} />
- </div>
- </>
- )}
-
- {selectedType === "sms" && (
- <div>
- <Label htmlFor="phoneNumber">Phone Number</Label>
- <Input
- id="phoneNumber"
- placeholder="+1234567890"
- {...register("phoneNumber", {
- required: "Phone number is required",
- pattern: {
- value: /^\+[1-9]\d{1,14}$/,
- message: "Phone number must be in E.164 format (e.g., +14155552671)",
- },
- })}
- />
- <p className="text-xs text-neutral-500 mt-1">Use international E.164 format: +[country code][number]</p>
- {errors.phoneNumber && <p className="text-sm text-red-500 mt-1">{errors.phoneNumber.message}</p>}
- </div>
- )}
-
- {/* Monitor Selection */}
- <div className="space-y-2">
- <Label>Monitors</Label>
- <MultiSelect
- options={monitorOptions}
- value={selectedMonitorIds}
- onValueChange={setSelectedMonitorIds}
- placeholder="Select monitors..."
- searchPlaceholder="Search monitors..."
- emptyText="No monitors found."
- disabled={monitorsLoading}
- />
- <p className="text-xs text-neutral-500 dark:text-neutral-400">
- Leave empty to receive alerts from all monitors
- </p>
- </div>
-
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={closeDialog}>
- Cancel
- </Button>
- <Button
- type="submit"
- variant="success"
- disabled={!isFormValid() || createChannel.isPending || updateChannel.isPending}
- >
- {editingChannel
- ? updateChannel.isPending
- ? "Updating..."
- : "Update Channel"
- : createChannel.isPending
- ? "Creating..."
- : "Create Channel"}
- </Button>
- </div>
- </form>
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/client/src/app/uptime/notifications/constants.ts b/client/src/app/uptime/notifications/constants.ts
deleted file mode 100644
index a9b954b80..000000000
--- a/client/src/app/uptime/notifications/constants.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Mail, Smartphone } from "lucide-react";
-import { SiDiscord, SiSlack } from "@icons-pack/react-simple-icons";
-
-export interface ChannelConfigItem {
- icon: typeof Mail;
- title: string;
- description: string;
- disabled?: boolean;
-}
-
-export const CHANNEL_CONFIG: Record<string, ChannelConfigItem> = {
- email: {
- icon: Mail,
- title: "Email",
- description: "Send notifications to an email address",
- },
- discord: {
- icon: SiDiscord,
- title: "Discord",
- description: "Send notifications to a Discord channel via webhook",
- },
- slack: {
- icon: SiSlack,
- title: "Slack",
- description: "Send notifications to a Slack channel",
- },
- sms: {
- icon: Smartphone,
- title: "SMS",
- description: "Send notifications via SMS",
- },
-};
diff --git a/client/src/app/uptime/notifications/notificationsStore.ts b/client/src/app/uptime/notifications/notificationsStore.ts
deleted file mode 100644
index 5fc968e0e..000000000
--- a/client/src/app/uptime/notifications/notificationsStore.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { create } from "zustand";
-import { NotificationChannel } from "@/api/uptime/notifications";
-
-type ChannelType = NotificationChannel["type"];
-
-interface NotificationsStore {
- // Dialog state
- isDialogOpen: boolean;
- selectedType: ChannelType | null;
- editingChannel: NotificationChannel | null;
-
- // Actions
- openDialog: (type: ChannelType, channel?: NotificationChannel) => void;
- closeDialog: () => void;
- resetForm: () => void;
-}
-
-export const useNotificationsStore = create<NotificationsStore>(set => ({
- // Initial state
- isDialogOpen: false,
- selectedType: null,
- editingChannel: null,
-
- // Actions
- openDialog: (type, channel) =>
- set({
- isDialogOpen: true,
- selectedType: type,
- editingChannel: channel || null,
- }),
-
- closeDialog: () =>
- set({
- isDialogOpen: false,
- editingChannel: null,
- }),
-
- resetForm: () =>
- set({
- selectedType: null,
- editingChannel: null,
- }),
-}));
diff --git a/client/src/app/uptime/notifications/page.tsx b/client/src/app/uptime/notifications/page.tsx
deleted file mode 100644
index ef4ecfe3e..000000000
--- a/client/src/app/uptime/notifications/page.tsx
+++ /dev/null
@@ -1,258 +0,0 @@
-"use client";
-
-import { ConfirmationModal } from "@/components/ConfirmationModal";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardTitle } from "@/components/ui/card";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Switch } from "@/components/ui/switch";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
-import { cn } from "@/lib/utils";
-import { Bell, Edit, MoreHorizontal, Power, Trash2 } from "lucide-react";
-import { useState } from "react";
-import { toast } from "@/components/ui/sonner";
-import {
- NotificationChannel,
- useDeleteChannel,
- useNotificationChannels,
- useTestChannel,
- useUpdateChannel,
-} from "../../../api/uptime/notifications";
-import { StandardPage } from "../../../components/StandardPage";
-import { NotificationDialog } from "./components/NotificationDialog";
-import { CHANNEL_CONFIG } from "./constants";
-import { useNotificationsStore } from "./notificationsStore";
-
-type ChannelType = NotificationChannel["type"];
-
-export default function NotificationsPage() {
- const { data, isLoading } = useNotificationChannels();
- const updateChannel = useUpdateChannel();
- const deleteChannel = useDeleteChannel();
- const testChannel = useTestChannel();
- const { openDialog } = useNotificationsStore();
- const [deleteModalOpen, setDeleteModalOpen] = useState(false);
- const [channelToDelete, setChannelToDelete] = useState<NotificationChannel | null>(null);
-
- const handleToggleChannel = async (channel: NotificationChannel) => {
- try {
- await updateChannel.mutateAsync({
- id: channel.id,
- data: { enabled: !channel.enabled },
- });
- toast.success(channel.enabled ? "Channel disabled" : "Channel enabled");
- } catch (error) {
- toast.error("Failed to update channel");
- }
- };
-
- const handleDeleteChannel = async () => {
- if (!channelToDelete) return;
-
- try {
- await deleteChannel.mutateAsync(channelToDelete.id);
- toast.success("Channel deleted");
- setChannelToDelete(null);
- } catch (error) {
- toast.error("Failed to delete channel");
- throw error; // Re-throw to show error in modal
- }
- };
-
- const openDeleteModal = (channel: NotificationChannel) => {
- setChannelToDelete(channel);
- setDeleteModalOpen(true);
- };
-
- const handleTestChannel = async (channel: NotificationChannel) => {
- try {
- await testChannel.mutateAsync(channel.id);
- toast.success("Test notification sent");
- } catch (error) {
- toast.error("Failed to send test notification");
- }
- };
-
- const openCreateDialog = (type: ChannelType) => {
- if (CHANNEL_CONFIG[type].disabled) {
- toast.info("This channel type is coming soon");
- return;
- }
- openDialog(type);
- };
-
- const openEditDialog = (channel: NotificationChannel) => {
- openDialog(channel.type, channel);
- };
-
- return (
- <>
- <div className="mb-6">
- <h1 className="text-2xl font-semibold">Notifications</h1>
- <p className="text-sm text-neutral-500 mt-1">Configure how you want to be notified about monitor incidents</p>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
- {Object.entries(CHANNEL_CONFIG).map(([type, config]) => {
- const Icon = config.icon;
- return (
- <div
- key={type}
- className={cn(
- "bg-neutral-900 border border-neutral-800 rounded-lg p-4 flex items-center justify-between"
- )}
- onClick={() => openCreateDialog(type as ChannelType)}
- >
- <div className="flex flex-col gap-2">
- <CardTitle className="flex items-center gap-2">
- <Icon className={cn("w-4 h-4")} />
- <span className="text-base">{config.title}</span>
- </CardTitle>
- <CardDescription>
- {config.description}
- {config.disabled && " - Coming soon"}
- </CardDescription>
- </div>
- <Button variant="success" disabled={config.disabled}>
- Create
- </Button>
- </div>
- );
- })}
- </div>
- <div className="space-y-4">
- <h2 className="text-lg font-medium">Active Channels</h2>
- {data?.channels?.length === 0 && !isLoading ? (
- <Card>
- <CardContent className="p-8 text-center text-neutral-500">
- No notification channels configured yet
- </CardContent>
- </Card>
- ) : (
- <Card>
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Channel</TableHead>
- <TableHead>Type</TableHead>
- <TableHead>Details</TableHead>
- <TableHead className="text-right">Actions</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {isLoading
- ? Array.from({ length: 3 }).map((_, i) => (
- <TableRow key={`skeleton-${i}`}>
- <TableCell>
- <div className="space-y-1">
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-3 w-16" />
- </div>
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-20" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-40" />
- </TableCell>
- <TableCell className="text-right">
- <Skeleton className="h-8 w-8 ml-auto" />
- </TableCell>
- </TableRow>
- ))
- : data?.channels?.map(channel => {
- const config = CHANNEL_CONFIG[channel.type];
- const Icon = config.icon;
- return (
- <TableRow key={channel.id}>
- <TableCell className="font-medium">
- <div className="flex items-center gap-2">
- {channel.name}
- {!channel.enabled && (
- <span className="text-xs bg-neutral-800 text-neutral-400 px-2 py-0.5 rounded">
- Disabled
- </span>
- )}
- </div>
- </TableCell>
- <TableCell>
- <div className="flex items-center gap-2">
- <Icon className="w-4 h-4" />
- <span className="capitalize">{channel.type}</span>
- </div>
- </TableCell>
- <TableCell className="text-sm text-neutral-500">
- {channel.type === "email" && channel.config?.email}
- {channel.type === "discord" && "Discord webhook"}
- {channel.type === "slack" && `Slack ${channel.config?.slackChannel || "webhook"}`}
- {channel.type === "sms" && channel.config?.phoneNumber}
- </TableCell>
- <TableCell className="text-right">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
- <MoreHorizontal className="h-4 w-4" />
- <span className="sr-only">Open menu</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => handleToggleChannel(channel)}>
- <Power className="h-4 w-4" />
- {channel.enabled ? "Disable" : "Enable"}
- </DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => handleTestChannel(channel)}
- disabled={!channel.enabled}
- >
- <Bell className="h-4 w-4" />
- Test
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => openEditDialog(channel)}>
- <Edit className="h-4 w-4" />
- Edit
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => openDeleteModal(channel)} className="text-red-600">
- <Trash2 className="h-4 w-4" />
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- </Card>
- )}
- </div>
- <NotificationDialog />
- <ConfirmationModal
- isOpen={deleteModalOpen}
- setIsOpen={setDeleteModalOpen}
- onConfirm={handleDeleteChannel}
- title="Delete Notification Channel"
- description={
- channelToDelete ? (
- <>
- Are you sure you want to delete the notification channel <strong>{channelToDelete.name}</strong>? This
- action cannot be undone.
- </>
- ) : (
- "Are you sure you want to delete this notification channel?"
- )
- }
- primaryAction={{
- children: "Delete Channel",
- variant: "destructive",
- }}
- />
- </>
- );
-}
diff --git a/client/src/app/uptime/page.tsx b/client/src/app/uptime/page.tsx
deleted file mode 100644
index 80f97d9c3..000000000
--- a/client/src/app/uptime/page.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { useEffect } from "react";
-
-export default function UptimePage() {
- const router = useRouter();
-
- useEffect(() => {
- router.replace("/uptime/monitors");
- }, [router]);
-
- return null;
-}
diff --git a/client/src/app/uptime/status-page/page.tsx b/client/src/app/uptime/status-page/page.tsx
deleted file mode 100644
index 612c5b7c4..000000000
--- a/client/src/app/uptime/status-page/page.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-export default function StatusPage() {
- return (
- <div className="flex items-center justify-between">
- <div>
- <h1 className="text-2xl font-semibold">Uptime Monitoring</h1>
- <p className="text-sm text-neutral-500 mt-1">Monitor the availability and performance of your endpoints</p>
- </div>
- </div>
- );
-}
diff --git a/client/src/proxy.ts b/client/src/proxy.ts
index a607bc6fc..b8d8918f2 100644
--- a/client/src/proxy.ts
+++ b/client/src/proxy.ts
@@ -43,7 +43,6 @@ export async function proxy(request: NextRequest) {
"admin",
"organization",
"account",
- "uptime",
"settings",
"rollup",
"as",
diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml
index 644c2744a..2178a56a5 100644
--- a/docker-compose.cloud.yml
+++ b/docker-compose.cloud.yml
@@ -85,10 +85,10 @@ services:
retries: 5
start_period: 5s
restart: unless-stopped
- # Backs session tracking and the BullMQ queues. noeviction is required by
- # BullMQ (evicting job keys corrupts queues); session keys carry a 30-minute
- # TTL so memory stays bounded by active-user count. AOF (everysec) keeps
- # queues durable across restarts.
+ # Backs session tracking, sticky identity, and bot-anomaly counters.
+ # noeviction keeps those keys from being dropped under memory pressure;
+ # session keys carry a 30-minute TTL so memory stays bounded by active-user
+ # count. AOF (everysec) keeps that state durable across restarts.
command:
- redis-server
- --requirepass
@@ -130,10 +130,6 @@ services:
- GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
- GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET}
- RESEND_API_KEY=${RESEND_API_KEY}
- # Twilio SMS configuration (cloud only)
- - TWILIO_ACCOUNT_SID=${TWILIO_ACCOUNT_SID}
- - TWILIO_AUTH_TOKEN=${TWILIO_AUTH_TOKEN}
- - TWILIO_PHONE_NUMBER=${TWILIO_PHONE_NUMBER}
# R2 storage for session replay (cloud only)
- R2_ACCOUNT_ID=${R2_ACCOUNT_ID}
- R2_ACCESS_KEY_ID=${R2_ACCESS_KEY_ID}
diff --git a/docker-compose.yml b/docker-compose.yml
index c59898ec2..2f40eafcc 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -85,10 +85,10 @@ services:
retries: 5
start_period: 5s
restart: unless-stopped
- # Backs session tracking and the BullMQ queues. noeviction is required by
- # BullMQ (evicting job keys corrupts queues); session keys carry a 30-minute
- # TTL so memory stays bounded by active-user count. AOF (everysec) keeps
- # queues durable across restarts.
+ # Backs session tracking, sticky identity, and bot-anomaly counters.
+ # noeviction keeps those keys from being dropped under memory pressure;
+ # session keys carry a 30-minute TTL so memory stays bounded by active-user
+ # count. AOF (everysec) keeps that state durable across restarts.
command:
- redis-server
- --requirepass
diff --git a/monitor-agent/.dockerignore b/monitor-agent/.dockerignore
deleted file mode 100644
index 64885306e..000000000
--- a/monitor-agent/.dockerignore
+++ /dev/null
@@ -1,19 +0,0 @@
-node_modules
-npm-debug.log
-.env
-.env.local
-.env.*.local
-dist
-.git
-.gitignore
-README.md
-.vscode
-.idea
-*.log
-.DS_Store
-coverage
-.nyc_output
-docker-compose*.yml
-Dockerfile*
-nginx.conf
-certs/
\ No newline at end of file
diff --git a/monitor-agent/.env.example b/monitor-agent/.env.example
deleted file mode 100644
index 5ce040d67..000000000
--- a/monitor-agent/.env.example
+++ /dev/null
@@ -1,39 +0,0 @@
-# Rybbit Monitor Agent Environment Configuration
-# Copy this file to .env and update with your values
-
-# Server Configuration
-PORT=3003
-HOST=0.0.0.0
-
-# Region Configuration
-# Use region codes like: us-east, us-west, eu-west, asia-pacific
-REGION=us-east
-
-# Security Configuration
-# Set ENABLE_IP_WHITELIST=true to enable IP whitelisting (optional)
-# If enabled, only IPs in ALLOWED_IPS can connect
-ENABLE_IP_WHITELIST=false
-
-# Space-separated list of IP addresses allowed to connect to this agent
-# Only used if ENABLE_IP_WHITELIST=true
-# These should be the IP addresses of your main Rybbit server
-# Example: ALLOWED_IPS="1.2.3.4 5.6.7.8"
-ALLOWED_IPS=
-
-# Domain Configuration (for Caddy SSL)
-# The domain name pointing to this monitor agent
-# Example: DOMAIN_NAME=us-east.monitor.yourdomain.com
-DOMAIN_NAME=
-
-# Timeout Configuration
-DEFAULT_TIMEOUT_MS=30000
-MAX_TIMEOUT_MS=60000
-
-# Logging
-# Options: error, warn, info, debug
-LOG_LEVEL=info
-
-# Docker Image Configuration (for docker-compose)
-# DOCKER_REGISTRY=ghcr.io
-# DOCKER_IMAGE=your-org/rybbit-monitor-agent
-# IMAGE_TAG=latest
\ No newline at end of file
diff --git a/monitor-agent/Caddyfile b/monitor-agent/Caddyfile
deleted file mode 100644
index dd0577ca4..000000000
--- a/monitor-agent/Caddyfile
+++ /dev/null
@@ -1,11 +0,0 @@
-# Caddyfile for Rybbit Monitor Agent
-{$DOMAIN_NAME} {
- # Enable compression
- encode zstd gzip
-
- # Set max request body size
- request_body max_size 10MB
-
- # Reverse proxy to monitor agent
- reverse_proxy monitor-agent:3003
-}
\ No newline at end of file
diff --git a/monitor-agent/Caddyfile.whitelist b/monitor-agent/Caddyfile.whitelist
deleted file mode 100644
index c331091ef..000000000
--- a/monitor-agent/Caddyfile.whitelist
+++ /dev/null
@@ -1,24 +0,0 @@
-# Caddyfile for Rybbit Monitor Agent with IP Whitelisting
-{$DOMAIN_NAME} {
- # Enable compression
- encode zstd gzip
-
- # Set max request body size
- request_body max_size 10MB
-
- # Handle requests based on IP whitelist
- @allowed {
- # The ALLOWED_IPS env var should contain space-separated IPs
- remote_ip {$ALLOWED_IPS}
- }
-
- # Proxy allowed requests to the monitor agent service
- handle @allowed {
- reverse_proxy monitor-agent:3003
- }
-
- # Block all non-whitelisted IPs
- handle {
- respond "Forbidden" 403
- }
-}
\ No newline at end of file
diff --git a/monitor-agent/DEPLOYMENT.md b/monitor-agent/DEPLOYMENT.md
deleted file mode 100644
index 56ece3404..000000000
--- a/monitor-agent/DEPLOYMENT.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# Rybbit Monitor Agent Deployment Guide
-
-This guide covers deploying the Rybbit Monitor Agent to VPS instances in different regions.
-
-## Prerequisites
-
-- VPS instances in desired regions (us-east, us-west, europe, asia)
-- Docker installed on each VPS
-- SSL certificates (or use Let's Encrypt)
-- Main Rybbit server IP address for whitelisting
-
-## Deployment Methods
-
-### Method 1: Docker Deployment (Recommended)
-
-#### 1. Initial Setup on VPS
-
-```bash
-# SSH into your VPS
-ssh user@your-vps-ip
-
-# Create directory for the agent
-sudo mkdir -p /opt/rybbit-monitor-agent
-cd /opt/rybbit-monitor-agent
-
-# Create environment file
-sudo nano .env
-```
-
-Add the following to `.env`:
-```env
-PORT=3003
-HOST=0.0.0.0
-REGION=us-east # Change based on region
-ALLOWED_IPS=1.2.3.4,5.6.7.8 # IP addresses of your main server
-DOMAIN_NAME=your-monitor-domain.com # Domain for this monitor agent
-LOG_LEVEL=info
-```
-
-#### 2. Deploy Using Docker Compose
-
-```bash
-# Download docker-compose files
-wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/docker-compose.yml
-wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/docker-compose.prod.yml
-wget https://raw.githubusercontent.com/your-repo/rybbit/main/monitor-agent/Caddyfile
-
-# Start the services
-REGION=us-east docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
-
-# Check status
-docker compose ps
-docker compose logs -f
-```
-
-#### 3. SSL Setup with Caddy
-
-Caddy automatically handles SSL certificates via Let's Encrypt. Simply ensure:
-1. Your domain points to the VPS
-2. Ports 80 and 443 are open
-3. The DOMAIN_NAME environment variable is set correctly
-
-```bash
-# SSL certificates will be automatically obtained when Caddy starts
-docker compose restart caddy
-```
-
-### Method 2: Automated Deployment Script
-
-Use the provided `deploy.sh` script from your local machine:
-
-```bash
-# Deploy to a specific region
-./deploy.sh us-east deploy
-
-# Deploy to all regions
-./deploy.sh all deploy
-
-# Check status of a region
-./deploy.sh us-east status
-
-# View logs from a region
-./deploy.sh us-east logs
-```
-
-Before using the script, update the server addresses in `deploy.sh`:
-```bash
-REGIONS["us-east"]="[email protected]"
-REGIONS["us-west"]="[email protected]"
-REGIONS["europe"]="[email protected]"
-REGIONS["asia"]="[email protected]"
-```
-
-### Method 3: Systemd Service (Alternative)
-
-For non-Docker deployments:
-
-```bash
-# Copy the systemd files to your VPS
-scp -r systemd/ user@your-vps:/tmp/
-
-# SSH into the VPS
-ssh user@your-vps
-
-# Run the setup script
-cd /tmp/systemd
-sudo ./setup.sh
-
-# Configure the environment
-sudo nano /opt/rybbit-monitor-agent/.env
-
-# Restart the service
-sudo systemctl restart rybbit-monitor-agent
-```
-
-## Post-Deployment Configuration
-
-### 1. Update Main Server Database
-
-Add the agent regions to your main Rybbit server database:
-
-```sql
-UPDATE agent_regions
-SET endpoint_url = 'https://us-east-monitor.example.com',
- enabled = true
-WHERE code = 'us-east';
-
-UPDATE agent_regions
-SET endpoint_url = 'https://us-west-monitor.example.com',
- enabled = true
-WHERE code = 'us-west';
-
-UPDATE agent_regions
-SET endpoint_url = 'https://europe-monitor.example.com',
- enabled = true
-WHERE code = 'europe';
-
-UPDATE agent_regions
-SET endpoint_url = 'https://asia-monitor.example.com',
- enabled = true
-WHERE code = 'asia';
-```
-
-### 2. Configure Firewall
-
-```bash
-# Allow HTTPS traffic
-sudo ufw allow 443/tcp
-
-# Allow HTTP traffic (for Let's Encrypt)
-sudo ufw allow 80/tcp
-
-# If not using Caddy proxy, allow agent port
-sudo ufw allow 3003/tcp
-```
-
-### 3. Setup Monitoring
-
-Monitor your agents using:
-
-1. **Health Endpoint**: `https://your-monitor-domain.com/health`
-2. **Metrics Endpoint**: `https://your-monitor-domain.com/metrics`
-3. **Main Server**: Check region health in the Rybbit UI
-
-## Security Considerations
-
-1. **IP Whitelisting**: Always configure `ALLOWED_IPS` in production
-2. **SSL/TLS**: Use HTTPS for all agent endpoints
-3. **Firewall**: Restrict access to only necessary ports
-4. **Updates**: Keep Docker images and dependencies updated
-5. **Monitoring**: Set up alerts for agent downtime
-
-## Troubleshooting
-
-### Check Agent Status
-```bash
-# Docker deployment
-docker compose logs monitor-agent
-curl http://localhost:3003/health
-
-# Systemd deployment
-sudo journalctl -u rybbit-monitor-agent -f
-sudo systemctl status rybbit-monitor-agent
-```
-
-### Common Issues
-
-1. **Connection refused**: Check firewall and ALLOWED_IPS configuration
-2. **SSL errors**: Verify certificates are properly installed
-3. **High memory usage**: Adjust Docker resource limits
-4. **Agent not responding**: Check logs and restart the service
-
-### Debug Mode
-
-Enable debug logging by setting `LOG_LEVEL=debug` in the `.env` file.
-
-## Maintenance
-
-### Update Agent
-```bash
-# Docker
-docker compose pull
-docker compose up -d
-
-# Systemd
-# Copy new files and restart
-sudo systemctl restart rybbit-monitor-agent
-```
-
-### Backup Configuration
-```bash
-# Backup environment file
-cp /opt/rybbit-monitor-agent/.env /opt/rybbit-monitor-agent/.env.backup
-```
-
-### Log Rotation
-
-Logs are automatically rotated with Docker. For systemd deployments, logrotate is configured during setup.
\ No newline at end of file
diff --git a/monitor-agent/Dockerfile b/monitor-agent/Dockerfile
deleted file mode 100644
index 932cc3b2e..000000000
--- a/monitor-agent/Dockerfile
+++ /dev/null
@@ -1,35 +0,0 @@
-FROM node:20-alpine
-
-# Install required system packages
-RUN apk add --no-cache \
- curl \
- bind-tools \
- iputils-ping
-
-WORKDIR /app
-
-# Copy package files
-COPY package*.json ./
-COPY tsconfig.json ./
-
-# Install all dependencies (including dev dependencies for build)
-RUN npm ci
-
-# Copy source code
-COPY src ./src
-
-# Build TypeScript
-RUN npm run build
-
-# Remove dev dependencies
-RUN npm prune --production
-
-# Expose port
-EXPOSE 3003
-
-# Health check
-HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
- CMD curl -f http://localhost:3003/health || exit 1
-
-# Run the application
-CMD ["node", "dist/index.js"]
\ No newline at end of file
diff --git a/monitor-agent/Dockerfile.dev b/monitor-agent/Dockerfile.dev
deleted file mode 100644
index 585341826..000000000
--- a/monitor-agent/Dockerfile.dev
+++ /dev/null
@@ -1,24 +0,0 @@
-FROM node:20-alpine
-
-# Install required system packages
-RUN apk add --no-cache \
- curl \
- bind-tools \
- iputils-ping
-
-WORKDIR /app
-
-# Copy package files
-COPY package*.json ./
-
-# Install all dependencies (including dev)
-RUN npm ci
-
-# Copy source code
-COPY . .
-
-# Expose port
-EXPOSE 3003
-
-# Run in development mode with hot reloading
-CMD ["npm", "run", "dev"]
\ No newline at end of file
diff --git a/monitor-agent/Makefile b/monitor-agent/Makefile
deleted file mode 100644
index b01e7fa1d..000000000
--- a/monitor-agent/Makefile
+++ /dev/null
@@ -1,67 +0,0 @@
-# Makefile for Rybbit Monitor Agent
-
-.PHONY: help build dev prod test clean deploy-all status-all
-
-# Default region
-REGION ?= us-east
-
-help: ## Show this help message
- @echo 'Usage: make [target] [REGION=region]'
- @echo ''
- @echo 'Targets:'
- @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
- @echo ''
- @echo 'Regions: us-east, us-west, europe, asia'
-
-build: ## Build the Docker image
- docker-compose build
-
-dev: ## Run in development mode with hot reloading
- docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
-
-prod: ## Run in production mode
- REGION=$(REGION) docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
-
-test: ## Run tests
- npm test
-
-lint: ## Run linter
- npm run lint
-
-clean: ## Clean up containers and images
- docker-compose down -v
- docker rmi rybbit-monitor-agent:latest || true
-
-logs: ## Show logs
- docker-compose logs -f monitor-agent
-
-shell: ## Open shell in container
- docker-compose exec monitor-agent sh
-
-deploy: ## Deploy to a specific region
- ./deploy.sh $(REGION) deploy
-
-deploy-all: ## Deploy to all regions
- @for region in us-east us-west europe asia; do \
- echo "Deploying to $$region..."; \
- ./deploy.sh $$region deploy; \
- done
-
-status: ## Check status of a specific region
- ./deploy.sh $(REGION) status
-
-status-all: ## Check status of all regions
- @for region in us-east us-west europe asia; do \
- echo "=== Status for $$region ==="; \
- ./deploy.sh $$region status; \
- echo ""; \
- done
-
-install: ## Install dependencies
- npm install
-
-build-ts: ## Build TypeScript
- npm run build
-
-start: ## Start the agent locally
- npm start
\ No newline at end of file
diff --git a/monitor-agent/README.md b/monitor-agent/README.md
deleted file mode 100644
index 23a28267d..000000000
--- a/monitor-agent/README.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Rybbit Monitor Agent
-
-Regional monitoring agent for Rybbit uptime monitoring system. This lightweight service runs on VPS instances in different regions to execute monitoring checks.
-
-## Features
-
-- HTTP/HTTPS monitoring with detailed timing information
-- TCP port monitoring
-- DNS monitoring (coming soon)
-- SMTP monitoring (coming soon)
-- PING monitoring (coming soon)
-- Authentication via API key
-- Health check endpoint
-- Prometheus metrics (coming soon)
-
-## Deployment
-
-### 1. Environment Configuration
-
-Copy `.env.example` to `.env` and configure:
-
-```bash
-cp .env.example .env
-```
-
-Key configuration:
-- `REGION`: Unique identifier for this region (e.g., 'us-east', 'europe')
-- `API_KEY`: Shared secret with main server
-- `ALLOWED_IPS`: Optional IP whitelist for main server
-
-### 2. Docker Deployment
-
-Build and run with Docker:
-
-```bash
-# Build
-docker build -t monitor-agent .
-
-# Run
-docker run -d \
- --name monitor-agent \
- -p 3003:3003 \
- --env-file .env \
- --restart always \
- monitor-agent
-```
-
-### 3. Docker Compose
-
-```yaml
-version: '3.8'
-services:
- monitor-agent:
- build: .
- ports:
- - "3003:3003"
- env_file:
- - .env
- restart: always
- healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:3003/health"]
- interval: 30s
- timeout: 10s
- retries: 3
-```
-
-### 4. Direct Node.js
-
-```bash
-# Install dependencies
-npm install
-
-# Build
-npm run build
-
-# Run
-npm start
-```
-
-## API Endpoints
-
-### POST /execute
-Execute a monitoring check.
-
-Request:
-```json
-{
- "jobId": "unique-job-id",
- "monitorId": 123,
- "monitorType": "http",
- "config": {
- "url": "https://example.com",
- "method": "GET",
- "timeoutMs": 30000
- },
- "validationRules": []
-}
-```
-
-Response:
-```json
-{
- "jobId": "unique-job-id",
- "region": "us-east",
- "status": "success",
- "responseTimeMs": 234,
- "statusCode": 200,
- "headers": {},
- "timing": {
- "dnsMs": 12,
- "tcpMs": 45,
- "tlsMs": 67,
- "ttfbMs": 123,
- "transferMs": 111
- }
-}
-```
-
-### GET /health
-Health check endpoint.
-
-### GET /metrics
-Prometheus metrics endpoint (coming soon).
-
-## Regional Deployment
-
-### Recommended VPS Providers
-
-1. **US-East**: DigitalOcean NYC, Vultr New Jersey
-2. **US-West**: Vultr Los Angeles, Linode Fremont
-3. **Europe**: Hetzner Frankfurt, DigitalOcean Amsterdam
-4. **Asia**: Vultr Singapore, Linode Tokyo
-
-### Deployment Script
-
-```bash
-#!/bin/bash
-REGION=$1
-DOCKER_IMAGE="your-registry.com/monitor-agent:$REGION"
-
-# Build and push
-docker build -t $DOCKER_IMAGE .
-docker push $DOCKER_IMAGE
-
-# Deploy to VPS
-ssh $REGION_HOST << EOF
- docker pull $DOCKER_IMAGE
- docker stop monitor-agent || true
- docker rm monitor-agent || true
- docker run -d \
- --name monitor-agent \
- -p 443:3003 \
- --env-file /etc/monitor-agent/.env \
- --restart always \
- $DOCKER_IMAGE
-EOF
-```
-
-## Security Considerations
-
-1. Always use HTTPS in production (reverse proxy with Caddy)
-2. Keep API keys secure and rotate regularly
-3. Use IP whitelisting when possible
-4. Monitor agent logs for suspicious activity
-5. Keep the agent updated with security patches
-
-## Monitoring the Monitor
-
-The main server should health check each agent:
-- Check `/health` endpoint every 30 seconds
-- Alert if agent is down
-- Automatic failover to other regions if needed
\ No newline at end of file
diff --git a/monitor-agent/deploy.sh b/monitor-agent/deploy.sh
deleted file mode 100755
index 576c2c4a7..000000000
--- a/monitor-agent/deploy.sh
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/bin/bash
-
-# Deploy script for monitor agents
-# Usage: ./deploy.sh [region] [action]
-# Example: ./deploy.sh us-east deploy
-
-set -e
-
-REGION=${1:-us-east}
-ACTION=${2:-deploy}
-DOCKER_REGISTRY=${DOCKER_REGISTRY:-docker.io}
-DOCKER_IMAGE=${DOCKER_IMAGE:-rybbit/monitor-agent}
-VERSION=${VERSION:-latest}
-
-# Region configurations
-declare -A REGIONS
-REGIONS["us-east"]="[email protected]"
-REGIONS["us-west"]="[email protected]"
-REGIONS["europe"]="[email protected]"
-REGIONS["asia"]="[email protected]"
-
-# Colors for output
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
-NC='\033[0m' # No Color
-
-# Functions
-log_info() {
- echo -e "${GREEN}[INFO]${NC} $1"
-}
-
-log_warn() {
- echo -e "${YELLOW}[WARN]${NC} $1"
-}
-
-log_error() {
- echo -e "${RED}[ERROR]${NC} $1"
-}
-
-# Check if region exists
-if [[ ! ${REGIONS[$REGION]} ]]; then
- log_error "Unknown region: $REGION"
- echo "Available regions: ${!REGIONS[@]}"
- exit 1
-fi
-
-SERVER=${REGIONS[$REGION]}
-
-case $ACTION in
- build)
- log_info "Building Docker image for $REGION..."
- docker build -t $DOCKER_IMAGE:$REGION .
- docker tag $DOCKER_IMAGE:$REGION $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
- docker tag $DOCKER_IMAGE:$REGION $DOCKER_REGISTRY/$DOCKER_IMAGE:$VERSION
- ;;
-
- push)
- log_info "Pushing Docker image for $REGION..."
- docker push $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
- docker push $DOCKER_REGISTRY/$DOCKER_IMAGE:$VERSION
- ;;
-
- deploy)
- log_info "Deploying to $REGION ($SERVER)..."
-
- # Build and push first
- $0 $REGION build
- $0 $REGION push
-
- # Deploy to server
- ssh $SERVER << EOF
- set -e
-
- # Create directories
- mkdir -p /opt/rybbit-monitor-agent
- cd /opt/rybbit-monitor-agent
-
- # Create .env file if it doesn't exist
- if [ ! -f .env ]; then
- echo "Creating .env file..."
- cat > .env << 'ENVFILE'
-PORT=3003
-HOST=0.0.0.0
-REGION=$REGION
-ALLOWED_IPS=\${ALLOWED_IPS:-}
-LOG_LEVEL=info
-ENVFILE
- echo "Please edit /opt/rybbit-monitor-agent/.env with correct values"
- fi
-
- # Pull latest image
- docker pull $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
-
- # Stop existing container
- docker stop rybbit-monitor-agent 2>/dev/null || true
- docker rm rybbit-monitor-agent 2>/dev/null || true
-
- # Start new container
- docker run -d \
- --name rybbit-monitor-agent \
- --restart always \
- -p 3003:3003 \
- --env-file .env \
- -e REGION=$REGION \
- $DOCKER_REGISTRY/$DOCKER_IMAGE:$REGION
-
- # Check if container is running
- sleep 5
- if docker ps | grep -q rybbit-monitor-agent; then
- echo "Container started successfully"
- docker logs --tail 20 rybbit-monitor-agent
- else
- echo "Container failed to start"
- docker logs rybbit-monitor-agent
- exit 1
- fi
-EOF
- log_info "Deployment to $REGION completed!"
- ;;
-
- status)
- log_info "Checking status of $REGION ($SERVER)..."
- ssh $SERVER << EOF
- echo "=== Container Status ==="
- docker ps -a | grep rybbit-monitor-agent || echo "No container found"
- echo ""
- echo "=== Recent Logs ==="
- docker logs --tail 20 rybbit-monitor-agent 2>&1 || echo "No logs available"
- echo ""
- echo "=== Health Check ==="
- curl -s http://localhost:3003/health | jq . || echo "Health check failed"
-EOF
- ;;
-
- logs)
- log_info "Fetching logs from $REGION ($SERVER)..."
- ssh $SERVER "docker logs --tail 100 -f rybbit-monitor-agent"
- ;;
-
- restart)
- log_info "Restarting $REGION ($SERVER)..."
- ssh $SERVER "docker restart rybbit-monitor-agent"
- ;;
-
- stop)
- log_info "Stopping $REGION ($SERVER)..."
- ssh $SERVER "docker stop rybbit-monitor-agent"
- ;;
-
- *)
- echo "Usage: $0 [region] [action]"
- echo "Regions: ${!REGIONS[@]}"
- echo "Actions: build, push, deploy, status, logs, restart, stop"
- exit 1
- ;;
-esac
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.dev.yml b/monitor-agent/docker-compose.dev.yml
deleted file mode 100644
index 8dc48d4b9..000000000
--- a/monitor-agent/docker-compose.dev.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-# Development-specific configuration
-services:
- monitor-agent:
- build:
- context: .
- dockerfile: Dockerfile.dev
- volumes:
- # Mount source code for hot reloading
- - ./src:/app/src:ro
- - ./package.json:/app/package.json:ro
- - ./tsconfig.json:/app/tsconfig.json:ro
- # Exclude node_modules
- - /app/node_modules
- environment:
- # Development overrides
- - LOG_LEVEL=debug
- - NODE_ENV=development
- command: npm run dev
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.prod.yml b/monitor-agent/docker-compose.prod.yml
deleted file mode 100644
index 9af53410b..000000000
--- a/monitor-agent/docker-compose.prod.yml
+++ /dev/null
@@ -1,65 +0,0 @@
-# Production deployment with multiple regions
-# Usage: REGION=us-east docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
-
-services:
- monitor-agent:
- image: ${DOCKER_REGISTRY:-docker.io}/${DOCKER_IMAGE:-rybbit/monitor-agent}:${REGION:-latest}
- restart: always
-
- # Production logging
- logging:
- driver: "json-file"
- options:
- max-size: "50m"
- max-file: "10"
- labels: "region,service"
-
- # Health monitoring
- labels:
- - "prometheus.io/scrape=true"
- - "prometheus.io/port=3003"
- - "prometheus.io/path=/metrics"
- - "region=${REGION}"
- - "service=monitor-agent"
-
- # Production resource limits
- deploy:
- resources:
- limits:
- cpus: '1'
- memory: 1G
- reservations:
- cpus: '0.5'
- memory: 512M
-
- # Restart policy
- restart_policy:
- condition: any
- delay: 5s
- max_attempts: 3
- window: 120s
-
- # Caddy with automatic SSL
- caddy:
- image: caddy:2.10.0
- container_name: rybbit-monitor-caddy-${REGION}
- ports:
- - "443:443"
- - "80:80"
- - "443:443/udp" # Needed for HTTP/3
- volumes:
- - ./Caddyfile:/etc/caddy/Caddyfile
- - caddy_data:/data
- - caddy_config:/config
- environment:
- - DOMAIN_NAME=${DOMAIN_NAME}
- - ALLOWED_IPS=${ALLOWED_IPS}
- depends_on:
- - monitor-agent
- restart: always
- networks:
- - monitor-network
-
-volumes:
- caddy_data:
- caddy_config:
\ No newline at end of file
diff --git a/monitor-agent/docker-compose.yml b/monitor-agent/docker-compose.yml
deleted file mode 100644
index db99c4982..000000000
--- a/monitor-agent/docker-compose.yml
+++ /dev/null
@@ -1,92 +0,0 @@
-services:
- monitor-agent:
- build:
- context: .
- dockerfile: Dockerfile
- container_name: rybbit-monitor-agent
- ports:
- - "${PORT:-3003}:3003"
- environment:
- # Server Configuration
- - PORT=${PORT:-3003}
- - HOST=${HOST:-0.0.0.0}
-
- # Region Configuration
- - REGION=${REGION:-us-east}
-
- # Security
- - ALLOWED_IPS=${ALLOWED_IPS:-}
-
- # Monitoring Defaults
- - DEFAULT_TIMEOUT_MS=${DEFAULT_TIMEOUT_MS:-30000}
- - MAX_TIMEOUT_MS=${MAX_TIMEOUT_MS:-60000}
-
- # Logging
- - LOG_LEVEL=${LOG_LEVEL:-info}
-
- # Use .env file if it exists
- env_file:
- - .env
-
- restart: unless-stopped
-
- healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:3003/health"]
- interval: 30s
- timeout: 10s
- start_period: 40s
- retries: 3
-
- # Resource limits
- deploy:
- resources:
- limits:
- cpus: "0.5"
- memory: 512M
- reservations:
- cpus: "0.25"
- memory: 256M
-
- # Logging configuration
- logging:
- driver: "json-file"
- options:
- max-size: "10m"
- max-file: "3"
-
- # Network configuration
- networks:
- - monitor-network
-
- # Caddy reverse proxy for HTTPS
- caddy:
- image: caddy:2.10.0
- container_name: rybbit-monitor-caddy
- ports:
- - "443:443"
- - "80:80"
- - "443:443/udp" # Needed for HTTP/3
- volumes:
- - ./Caddyfile${ENABLE_IP_WHITELIST:+.whitelist}:/etc/caddy/Caddyfile
- - caddy_data:/data
- - caddy_config:/config
- environment:
- - DOMAIN_NAME=${DOMAIN_NAME}
- - ALLOWED_IPS=${ALLOWED_IPS}
- depends_on:
- - monitor-agent
- restart: unless-stopped
- networks:
- - monitor-network
- profiles:
- - with-ssl
-
-networks:
- monitor-network:
- driver: bridge
-
-# Volumes for persistent data
-volumes:
- monitor-data:
- caddy_data:
- caddy_config:
diff --git a/monitor-agent/package-lock.json b/monitor-agent/package-lock.json
deleted file mode 100644
index df6b45755..000000000
--- a/monitor-agent/package-lock.json
+++ /dev/null
@@ -1,1566 +0,0 @@
-{
- "name": "rybbit-monitor-agent",
- "version": "1.0.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "rybbit-monitor-agent",
- "version": "1.0.0",
- "dependencies": {
- "@fastify/cors": "^8.5.0",
- "@fastify/rate-limit": "^9.1.0",
- "dns-packet": "^5.6.1",
- "dotenv": "^16.3.1",
- "fastify": "^4.25.0",
- "nodemailer": "^6.9.8",
- "ping": "^0.4.4",
- "pino": "^8.17.0",
- "pino-pretty": "^10.3.0",
- "undici": "^6.2.0",
- "zod": "^3.22.4"
- },
- "devDependencies": {
- "@types/node": "^20.10.0",
- "@types/nodemailer": "^6.4.14",
- "@types/ping": "^0.4.4",
- "tsx": "^4.6.0",
- "typescript": "^5.3.0"
- }
- },
- "node_modules/@esbuild/aix-ppc64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.8.tgz",
- "integrity": "sha512-urAvrUedIqEiFR3FYSLTWQgLu5tb+m0qZw0NBEasUeo6wuqatkMDaRT+1uABiGXEu5vqgPd7FGE1BhsAIy9QVA==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-arm": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.8.tgz",
- "integrity": "sha512-RONsAvGCz5oWyePVnLdZY/HHwA++nxYWIX1atInlaW6SEkwq6XkP3+cb825EUcRs5Vss/lGh/2YxAb5xqc07Uw==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.8.tgz",
- "integrity": "sha512-OD3p7LYzWpLhZEyATcTSJ67qB5D+20vbtr6vHlHWSQYhKtzUYrETuWThmzFpZtFsBIxRvhO07+UgVA9m0i/O1w==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/android-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.8.tgz",
- "integrity": "sha512-yJAVPklM5+4+9dTeKwHOaA+LQkmrKFX96BM0A/2zQrbS6ENCmxc4OVoBs5dPkCCak2roAD+jKCdnmOqKszPkjA==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/darwin-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.8.tgz",
- "integrity": "sha512-Jw0mxgIaYX6R8ODrdkLLPwBqHTtYHJSmzzd+QeytSugzQ0Vg4c5rDky5VgkoowbZQahCbsv1rT1KW72MPIkevw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/darwin-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.8.tgz",
- "integrity": "sha512-Vh2gLxxHnuoQ+GjPNvDSDRpoBCUzY4Pu0kBqMBDlK4fuWbKgGtmDIeEC081xi26PPjn+1tct+Bh8FjyLlw1Zlg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/freebsd-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.8.tgz",
- "integrity": "sha512-YPJ7hDQ9DnNe5vxOm6jaie9QsTwcKedPvizTVlqWG9GBSq+BuyWEDazlGaDTC5NGU4QJd666V0yqCBL2oWKPfA==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/freebsd-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.8.tgz",
- "integrity": "sha512-MmaEXxQRdXNFsRN/KcIimLnSJrk2r5H8v+WVafRWz5xdSVmWLoITZQXcgehI2ZE6gioE6HirAEToM/RvFBeuhw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-arm": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.8.tgz",
- "integrity": "sha512-FuzEP9BixzZohl1kLf76KEVOsxtIBFwCaLupVuk4eFVnOZfU+Wsn+x5Ryam7nILV2pkq2TqQM9EZPsOBuMC+kg==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.8.tgz",
- "integrity": "sha512-WIgg00ARWv/uYLU7lsuDK00d/hHSfES5BzdWAdAig1ioV5kaFNrtK8EqGcUBJhYqotlUByUKz5Qo6u8tt7iD/w==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-ia32": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.8.tgz",
- "integrity": "sha512-A1D9YzRX1i+1AJZuFFUMP1E9fMaYY+GnSQil9Tlw05utlE86EKTUA7RjwHDkEitmLYiFsRd9HwKBPEftNdBfjg==",
- "cpu": [
- "ia32"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-loong64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.8.tgz",
- "integrity": "sha512-O7k1J/dwHkY1RMVvglFHl1HzutGEFFZ3kNiDMSOyUrB7WcoHGf96Sh+64nTRT26l3GMbCW01Ekh/ThKM5iI7hQ==",
- "cpu": [
- "loong64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-mips64el": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.8.tgz",
- "integrity": "sha512-uv+dqfRazte3BzfMp8PAQXmdGHQt2oC/y2ovwpTteqrMx2lwaksiFZ/bdkXJC19ttTvNXBuWH53zy/aTj1FgGw==",
- "cpu": [
- "mips64el"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-ppc64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.8.tgz",
- "integrity": "sha512-GyG0KcMi1GBavP5JgAkkstMGyMholMDybAf8wF5A70CALlDM2p/f7YFE7H92eDeH/VBtFJA5MT4nRPDGg4JuzQ==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-riscv64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.8.tgz",
- "integrity": "sha512-rAqDYFv3yzMrq7GIcen3XP7TUEG/4LK86LUPMIz6RT8A6pRIDn0sDcvjudVZBiiTcZCY9y2SgYX2lgK3AF+1eg==",
- "cpu": [
- "riscv64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-s390x": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.8.tgz",
- "integrity": "sha512-Xutvh6VjlbcHpsIIbwY8GVRbwoviWT19tFhgdA7DlenLGC/mbc3lBoVb7jxj9Z+eyGqvcnSyIltYUrkKzWqSvg==",
- "cpu": [
- "s390x"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/linux-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.8.tgz",
- "integrity": "sha512-ASFQhgY4ElXh3nDcOMTkQero4b1lgubskNlhIfJrsH5OKZXDpUAKBlNS0Kx81jwOBp+HCeZqmoJuihTv57/jvQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/netbsd-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.8.tgz",
- "integrity": "sha512-d1KfruIeohqAi6SA+gENMuObDbEjn22olAR7egqnkCD9DGBG0wsEARotkLgXDu6c4ncgWTZJtN5vcgxzWRMzcw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/netbsd-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.8.tgz",
- "integrity": "sha512-nVDCkrvx2ua+XQNyfrujIG38+YGyuy2Ru9kKVNyh5jAys6n+l44tTtToqHjino2My8VAY6Lw9H7RI73XFi66Cg==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openbsd-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.8.tgz",
- "integrity": "sha512-j8HgrDuSJFAujkivSMSfPQSAa5Fxbvk4rgNAS5i3K+r8s1X0p1uOO2Hl2xNsGFppOeHOLAVgYwDVlmxhq5h+SQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openbsd-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.8.tgz",
- "integrity": "sha512-1h8MUAwa0VhNCDp6Af0HToI2TJFAn1uqT9Al6DJVzdIBAd21m/G0Yfc77KDM3uF3T/YaOgQq3qTJHPbTOInaIQ==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/openharmony-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.8.tgz",
- "integrity": "sha512-r2nVa5SIK9tSWd0kJd9HCffnDHKchTGikb//9c7HX+r+wHYCpQrSgxhlY6KWV1nFo1l4KFbsMlHk+L6fekLsUg==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "openharmony"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/sunos-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.8.tgz",
- "integrity": "sha512-zUlaP2S12YhQ2UzUfcCuMDHQFJyKABkAjvO5YSndMiIkMimPmxA+BYSBikWgsRpvyxuRnow4nS5NPnf9fpv41w==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "sunos"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-arm64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.8.tgz",
- "integrity": "sha512-YEGFFWESlPva8hGL+zvj2z/SaK+pH0SwOM0Nc/d+rVnW7GSTFlLBGzZkuSU9kFIGIo8q9X3ucpZhu8PDN5A2sQ==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-ia32": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.8.tgz",
- "integrity": "sha512-hiGgGC6KZ5LZz58OL/+qVVoZiuZlUYlYHNAmczOm7bs2oE1XriPFi5ZHHrS8ACpV5EjySrnoCKmcbQMN+ojnHg==",
- "cpu": [
- "ia32"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@esbuild/win32-x64": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.8.tgz",
- "integrity": "sha512-cn3Yr7+OaaZq1c+2pe+8yxC8E144SReCQjN6/2ynubzYjvyqZjTXfQJpAcQpsdJq3My7XADANiYGHoFC69pLQw==",
- "cpu": [
- "x64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/@fastify/ajv-compiler": {
- "version": "3.6.0",
- "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-3.6.0.tgz",
- "integrity": "sha512-LwdXQJjmMD+GwLOkP7TVC68qa+pSSogeWWmznRJ/coyTcfe9qA05AHFSe1eZFwK6q+xVRpChnvFUkf1iYaSZsQ==",
- "license": "MIT",
- "dependencies": {
- "ajv": "^8.11.0",
- "ajv-formats": "^2.1.1",
- "fast-uri": "^2.0.0"
- }
- },
- "node_modules/@fastify/cors": {
- "version": "8.5.0",
- "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-8.5.0.tgz",
- "integrity": "sha512-/oZ1QSb02XjP0IK1U0IXktEsw/dUBTxJOW7IpIeO8c/tNalw/KjoNSJv1Sf6eqoBPO+TDGkifq6ynFK3v68HFQ==",
- "license": "MIT",
- "dependencies": {
- "fastify-plugin": "^4.0.0",
- "mnemonist": "0.39.6"
- }
- },
- "node_modules/@fastify/error": {
- "version": "3.4.1",
- "resolved": "https://registry.npmjs.org/@fastify/error/-/error-3.4.1.tgz",
- "integrity": "sha512-wWSvph+29GR783IhmvdwWnN4bUxTD01Vm5Xad4i7i1VuAOItLvbPAb69sb0IQ2N57yprvhNIwAP5B6xfKTmjmQ==",
- "license": "MIT"
- },
- "node_modules/@fastify/fast-json-stringify-compiler": {
- "version": "4.3.0",
- "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-4.3.0.tgz",
- "integrity": "sha512-aZAXGYo6m22Fk1zZzEUKBvut/CIIQe/BapEORnxiD5Qr0kPHqqI69NtEMCme74h+at72sPhbkb4ZrLd1W3KRLA==",
- "license": "MIT",
- "dependencies": {
- "fast-json-stringify": "^5.7.0"
- }
- },
- "node_modules/@fastify/merge-json-schemas": {
- "version": "0.1.1",
- "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.1.1.tgz",
- "integrity": "sha512-fERDVz7topgNjtXsJTTW1JKLy0rhuLRcquYqNR9rF7OcVpCa2OVW49ZPDIhaRRCaUuvVxI+N416xUoF76HNSXA==",
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.3"
- }
- },
- "node_modules/@fastify/rate-limit": {
- "version": "9.1.0",
- "resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-9.1.0.tgz",
- "integrity": "sha512-h5dZWCkuZXN0PxwqaFQLxeln8/LNwQwH9popywmDCFdKfgpi4b/HoMH1lluy6P+30CG9yzzpSpwTCIPNB9T1JA==",
- "license": "MIT",
- "dependencies": {
- "@lukeed/ms": "^2.0.1",
- "fastify-plugin": "^4.0.0",
- "toad-cache": "^3.3.1"
- }
- },
- "node_modules/@leichtgewicht/ip-codec": {
- "version": "2.0.5",
- "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
- "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
- "license": "MIT"
- },
- "node_modules/@lukeed/ms": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz",
- "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/@types/node": {
- "version": "20.19.9",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.9.tgz",
- "integrity": "sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "undici-types": "~6.21.0"
- }
- },
- "node_modules/@types/nodemailer": {
- "version": "6.4.17",
- "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.17.tgz",
- "integrity": "sha512-I9CCaIp6DTldEg7vyUTZi8+9Vo0hi1/T8gv3C89yk1rSAAzoKQ8H8ki/jBYJSFoH/BisgLP8tkZMlQ91CIquww==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/node": "*"
- }
- },
- "node_modules/@types/ping": {
- "version": "0.4.4",
- "resolved": "https://registry.npmjs.org/@types/ping/-/ping-0.4.4.tgz",
- "integrity": "sha512-ifvo6w2f5eJYlXm+HiVx67iJe8WZp87sfa683nlqED5Vnt9Z93onkokNoWqOG21EaE8fMxyKPobE+mkPEyxsdw==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/abort-controller": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
- "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
- "license": "MIT",
- "dependencies": {
- "event-target-shim": "^5.0.0"
- },
- "engines": {
- "node": ">=6.5"
- }
- },
- "node_modules/abstract-logging": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",
- "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
- "license": "MIT"
- },
- "node_modules/ajv": {
- "version": "8.17.1",
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
- "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.3",
- "fast-uri": "^3.0.1",
- "json-schema-traverse": "^1.0.0",
- "require-from-string": "^2.0.2"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/epoberezkin"
- }
- },
- "node_modules/ajv-formats": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
- "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
- "license": "MIT",
- "dependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependenciesMeta": {
- "ajv": {
- "optional": true
- }
- }
- },
- "node_modules/ajv/node_modules/fast-uri": {
- "version": "3.0.6",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz",
- "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "BSD-3-Clause"
- },
- "node_modules/atomic-sleep": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
- "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",
- "license": "MIT",
- "engines": {
- "node": ">=8.0.0"
- }
- },
- "node_modules/avvio": {
- "version": "8.4.0",
- "resolved": "https://registry.npmjs.org/avvio/-/avvio-8.4.0.tgz",
- "integrity": "sha512-CDSwaxINFy59iNwhYnkvALBwZiTydGkOecZyPkqBpABYR1KqGEsET0VOOYDwtleZSUIdeY36DC2bSZ24CO1igA==",
- "license": "MIT",
- "dependencies": {
- "@fastify/error": "^3.3.0",
- "fastq": "^1.17.1"
- }
- },
- "node_modules/base64-js": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
- "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT"
- },
- "node_modules/buffer": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
- "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "base64-js": "^1.3.1",
- "ieee754": "^1.2.1"
- }
- },
- "node_modules/colorette": {
- "version": "2.0.20",
- "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
- "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
- "license": "MIT"
- },
- "node_modules/cookie": {
- "version": "0.7.2",
- "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
- "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/dateformat": {
- "version": "4.6.3",
- "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
- "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==",
- "license": "MIT",
- "engines": {
- "node": "*"
- }
- },
- "node_modules/dns-packet": {
- "version": "5.6.1",
- "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
- "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
- "license": "MIT",
- "dependencies": {
- "@leichtgewicht/ip-codec": "^2.0.1"
- },
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/dotenv": {
- "version": "16.6.1",
- "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
- "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
- "license": "BSD-2-Clause",
- "engines": {
- "node": ">=12"
- },
- "funding": {
- "url": "https://dotenvx.com"
- }
- },
- "node_modules/end-of-stream": {
- "version": "1.4.5",
- "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
- "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
- "license": "MIT",
- "dependencies": {
- "once": "^1.4.0"
- }
- },
- "node_modules/esbuild": {
- "version": "0.25.8",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.8.tgz",
- "integrity": "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q==",
- "dev": true,
- "hasInstallScript": true,
- "license": "MIT",
- "bin": {
- "esbuild": "bin/esbuild"
- },
- "engines": {
- "node": ">=18"
- },
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.25.8",
- "@esbuild/android-arm": "0.25.8",
- "@esbuild/android-arm64": "0.25.8",
- "@esbuild/android-x64": "0.25.8",
- "@esbuild/darwin-arm64": "0.25.8",
- "@esbuild/darwin-x64": "0.25.8",
- "@esbuild/freebsd-arm64": "0.25.8",
- "@esbuild/freebsd-x64": "0.25.8",
- "@esbuild/linux-arm": "0.25.8",
- "@esbuild/linux-arm64": "0.25.8",
- "@esbuild/linux-ia32": "0.25.8",
- "@esbuild/linux-loong64": "0.25.8",
- "@esbuild/linux-mips64el": "0.25.8",
- "@esbuild/linux-ppc64": "0.25.8",
- "@esbuild/linux-riscv64": "0.25.8",
- "@esbuild/linux-s390x": "0.25.8",
- "@esbuild/linux-x64": "0.25.8",
- "@esbuild/netbsd-arm64": "0.25.8",
- "@esbuild/netbsd-x64": "0.25.8",
- "@esbuild/openbsd-arm64": "0.25.8",
- "@esbuild/openbsd-x64": "0.25.8",
- "@esbuild/openharmony-arm64": "0.25.8",
- "@esbuild/sunos-x64": "0.25.8",
- "@esbuild/win32-arm64": "0.25.8",
- "@esbuild/win32-ia32": "0.25.8",
- "@esbuild/win32-x64": "0.25.8"
- }
- },
- "node_modules/event-target-shim": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
- "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/events": {
- "version": "3.3.0",
- "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
- "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
- "license": "MIT",
- "engines": {
- "node": ">=0.8.x"
- }
- },
- "node_modules/fast-content-type-parse": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-1.1.0.tgz",
- "integrity": "sha512-fBHHqSTFLVnR61C+gltJuE5GkVQMV0S2nqUO8TJ+5Z3qAKG8vAx4FKai1s5jq/inV1+sREynIWSuQ6HgoSXpDQ==",
- "license": "MIT"
- },
- "node_modules/fast-copy": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-3.0.2.tgz",
- "integrity": "sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==",
- "license": "MIT"
- },
- "node_modules/fast-decode-uri-component": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
- "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",
- "license": "MIT"
- },
- "node_modules/fast-deep-equal": {
- "version": "3.1.3",
- "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
- "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
- "license": "MIT"
- },
- "node_modules/fast-json-stringify": {
- "version": "5.16.1",
- "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-5.16.1.tgz",
- "integrity": "sha512-KAdnLvy1yu/XrRtP+LJnxbBGrhN+xXu+gt3EUvZhYGKCr3lFHq/7UFJHHFgmJKoqlh6B40bZLEv7w46B0mqn1g==",
- "license": "MIT",
- "dependencies": {
- "@fastify/merge-json-schemas": "^0.1.0",
- "ajv": "^8.10.0",
- "ajv-formats": "^3.0.1",
- "fast-deep-equal": "^3.1.3",
- "fast-uri": "^2.1.0",
- "json-schema-ref-resolver": "^1.0.1",
- "rfdc": "^1.2.0"
- }
- },
- "node_modules/fast-json-stringify/node_modules/ajv-formats": {
- "version": "3.0.1",
- "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
- "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
- "license": "MIT",
- "dependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependenciesMeta": {
- "ajv": {
- "optional": true
- }
- }
- },
- "node_modules/fast-querystring": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",
- "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==",
- "license": "MIT",
- "dependencies": {
- "fast-decode-uri-component": "^1.0.1"
- }
- },
- "node_modules/fast-redact": {
- "version": "3.5.0",
- "resolved": "https://registry.npmjs.org/fast-redact/-/fast-redact-3.5.0.tgz",
- "integrity": "sha512-dwsoQlS7h9hMeYUq1W++23NDcBLV4KqONnITDV9DjfS3q1SgDGVrBdvvTLUotWtPSD7asWDV9/CmsZPy8Hf70A==",
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
- "node_modules/fast-safe-stringify": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
- "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
- "license": "MIT"
- },
- "node_modules/fast-uri": {
- "version": "2.4.0",
- "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.0.tgz",
- "integrity": "sha512-ypuAmmMKInk5q7XcepxlnUWDLWv4GFtaJqAzWKqn62IpQ3pejtr5dTVbt3vwqVaMKmkNR55sTT+CqUKIaT21BA==",
- "license": "MIT"
- },
- "node_modules/fastify": {
- "version": "4.29.1",
- "resolved": "https://registry.npmjs.org/fastify/-/fastify-4.29.1.tgz",
- "integrity": "sha512-m2kMNHIG92tSNWv+Z3UeTR9AWLLuo7KctC7mlFPtMEVrfjIhmQhkQnT9v15qA/BfVq3vvj134Y0jl9SBje3jXQ==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT",
- "dependencies": {
- "@fastify/ajv-compiler": "^3.5.0",
- "@fastify/error": "^3.4.0",
- "@fastify/fast-json-stringify-compiler": "^4.3.0",
- "abstract-logging": "^2.0.1",
- "avvio": "^8.3.0",
- "fast-content-type-parse": "^1.1.0",
- "fast-json-stringify": "^5.8.0",
- "find-my-way": "^8.0.0",
- "light-my-request": "^5.11.0",
- "pino": "^9.0.0",
- "process-warning": "^3.0.0",
- "proxy-addr": "^2.0.7",
- "rfdc": "^1.3.0",
- "secure-json-parse": "^2.7.0",
- "semver": "^7.5.4",
- "toad-cache": "^3.3.0"
- }
- },
- "node_modules/fastify-plugin": {
- "version": "4.5.1",
- "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz",
- "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==",
- "license": "MIT"
- },
- "node_modules/fastify/node_modules/pino": {
- "version": "9.7.0",
- "resolved": "https://registry.npmjs.org/pino/-/pino-9.7.0.tgz",
- "integrity": "sha512-vnMCM6xZTb1WDmLvtG2lE/2p+t9hDEIvTWJsu6FejkE62vB7gDhvzrpFR4Cw2to+9JNQxVnkAKVPA1KPB98vWg==",
- "license": "MIT",
- "dependencies": {
- "atomic-sleep": "^1.0.0",
- "fast-redact": "^3.1.1",
- "on-exit-leak-free": "^2.1.0",
- "pino-abstract-transport": "^2.0.0",
- "pino-std-serializers": "^7.0.0",
- "process-warning": "^5.0.0",
- "quick-format-unescaped": "^4.0.3",
- "real-require": "^0.2.0",
- "safe-stable-stringify": "^2.3.1",
- "sonic-boom": "^4.0.1",
- "thread-stream": "^3.0.0"
- },
- "bin": {
- "pino": "bin.js"
- }
- },
- "node_modules/fastify/node_modules/pino-abstract-transport": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz",
- "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==",
- "license": "MIT",
- "dependencies": {
- "split2": "^4.0.0"
- }
- },
- "node_modules/fastify/node_modules/pino-std-serializers": {
- "version": "7.0.0",
- "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.0.0.tgz",
- "integrity": "sha512-e906FRY0+tV27iq4juKzSYPbUj2do2X2JX4EzSca1631EB2QJQUqGbDuERal7LCtOpxl6x3+nvo9NPZcmjkiFA==",
- "license": "MIT"
- },
- "node_modules/fastify/node_modules/pino/node_modules/process-warning": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",
- "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "MIT"
- },
- "node_modules/fastify/node_modules/sonic-boom": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz",
- "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==",
- "license": "MIT",
- "dependencies": {
- "atomic-sleep": "^1.0.0"
- }
- },
- "node_modules/fastify/node_modules/thread-stream": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
- "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==",
- "license": "MIT",
- "dependencies": {
- "real-require": "^0.2.0"
- }
- },
- "node_modules/fastq": {
- "version": "1.19.1",
- "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz",
- "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==",
- "license": "ISC",
- "dependencies": {
- "reusify": "^1.0.4"
- }
- },
- "node_modules/find-my-way": {
- "version": "8.2.2",
- "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-8.2.2.tgz",
- "integrity": "sha512-Dobi7gcTEq8yszimcfp/R7+owiT4WncAJ7VTTgFH1jYJ5GaG1FbhjwDG820hptN0QDFvzVY3RfCzdInvGPGzjA==",
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.3",
- "fast-querystring": "^1.0.0",
- "safe-regex2": "^3.1.0"
- },
- "engines": {
- "node": ">=14"
- }
- },
- "node_modules/forwarded": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
- "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/fsevents": {
- "version": "2.3.3",
- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
- "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
- "dev": true,
- "hasInstallScript": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
- }
- },
- "node_modules/get-tsconfig": {
- "version": "4.10.1",
- "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.10.1.tgz",
- "integrity": "sha512-auHyJ4AgMz7vgS8Hp3N6HXSmlMdUyhSUrfBF16w153rxtLIEOE+HGqaBppczZvnHLqQJfiHotCYpNhl0lUROFQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "resolve-pkg-maps": "^1.0.0"
- },
- "funding": {
- "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
- }
- },
- "node_modules/help-me": {
- "version": "5.0.0",
- "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
- "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
- "license": "MIT"
- },
- "node_modules/ieee754": {
- "version": "1.2.1",
- "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
- "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "BSD-3-Clause"
- },
- "node_modules/ipaddr.js": {
- "version": "1.9.1",
- "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
- "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.10"
- }
- },
- "node_modules/joycon": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
- "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
- "license": "MIT",
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/json-schema-ref-resolver": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz",
- "integrity": "sha512-EJAj1pgHc1hxF6vo2Z3s69fMjO1INq6eGHXZ8Z6wCQeldCuwxGK9Sxf4/cScGn3FZubCVUehfWtcDM/PLteCQw==",
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.3"
- }
- },
- "node_modules/json-schema-traverse": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
- "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
- "license": "MIT"
- },
- "node_modules/light-my-request": {
- "version": "5.14.0",
- "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-5.14.0.tgz",
- "integrity": "sha512-aORPWntbpH5esaYpGOOmri0OHDOe3wC5M2MQxZ9dvMLZm6DnaAn0kJlcbU9hwsQgLzmZyReKwFwwPkR+nHu5kA==",
- "license": "BSD-3-Clause",
- "dependencies": {
- "cookie": "^0.7.0",
- "process-warning": "^3.0.0",
- "set-cookie-parser": "^2.4.1"
- }
- },
- "node_modules/minimist": {
- "version": "1.2.8",
- "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
- "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/mnemonist": {
- "version": "0.39.6",
- "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.6.tgz",
- "integrity": "sha512-A/0v5Z59y63US00cRSLiloEIw3t5G+MiKz4BhX21FI+YBJXBOGW0ohFxTxO08dsOYlzxo87T7vGfZKYp2bcAWA==",
- "license": "MIT",
- "dependencies": {
- "obliterator": "^2.0.1"
- }
- },
- "node_modules/nodemailer": {
- "version": "6.10.1",
- "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.10.1.tgz",
- "integrity": "sha512-Z+iLaBGVaSjbIzQ4pX6XV41HrooLsQ10ZWPUehGmuantvzWoDVBnmsdUcOIDM1t+yPor5pDhVlDESgOMEGxhHA==",
- "license": "MIT-0",
- "engines": {
- "node": ">=6.0.0"
- }
- },
- "node_modules/obliterator": {
- "version": "2.0.5",
- "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
- "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==",
- "license": "MIT"
- },
- "node_modules/on-exit-leak-free": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
- "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",
- "license": "MIT",
- "engines": {
- "node": ">=14.0.0"
- }
- },
- "node_modules/once": {
- "version": "1.4.0",
- "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
- "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "license": "ISC",
- "dependencies": {
- "wrappy": "1"
- }
- },
- "node_modules/ping": {
- "version": "0.4.4",
- "resolved": "https://registry.npmjs.org/ping/-/ping-0.4.4.tgz",
- "integrity": "sha512-56ZMC0j7SCsMMLdOoUg12VZCfj/+ZO+yfOSjaNCRrmZZr6GLbN2X/Ui56T15dI8NhiHckaw5X2pvyfAomanwqQ==",
- "license": "MIT",
- "engines": {
- "node": ">=4.0.0"
- }
- },
- "node_modules/pino": {
- "version": "8.21.0",
- "resolved": "https://registry.npmjs.org/pino/-/pino-8.21.0.tgz",
- "integrity": "sha512-ip4qdzjkAyDDZklUaZkcRFb2iA118H9SgRh8yzTkSQK8HilsOJF7rSY8HoW5+I0M46AZgX/pxbprf2vvzQCE0Q==",
- "license": "MIT",
- "dependencies": {
- "atomic-sleep": "^1.0.0",
- "fast-redact": "^3.1.1",
- "on-exit-leak-free": "^2.1.0",
- "pino-abstract-transport": "^1.2.0",
- "pino-std-serializers": "^6.0.0",
- "process-warning": "^3.0.0",
- "quick-format-unescaped": "^4.0.3",
- "real-require": "^0.2.0",
- "safe-stable-stringify": "^2.3.1",
- "sonic-boom": "^3.7.0",
- "thread-stream": "^2.6.0"
- },
- "bin": {
- "pino": "bin.js"
- }
- },
- "node_modules/pino-abstract-transport": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-1.2.0.tgz",
- "integrity": "sha512-Guhh8EZfPCfH+PMXAb6rKOjGQEoy0xlAIn+irODG5kgfYV+BQ0rGYYWTIel3P5mmyXqkYkPmdIkywsn6QKUR1Q==",
- "license": "MIT",
- "dependencies": {
- "readable-stream": "^4.0.0",
- "split2": "^4.0.0"
- }
- },
- "node_modules/pino-pretty": {
- "version": "10.3.1",
- "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.3.1.tgz",
- "integrity": "sha512-az8JbIYeN/1iLj2t0jR9DV48/LQ3RC6hZPpapKPkb84Q+yTidMCpgWxIT3N0flnBDilyBQ1luWNpOeJptjdp/g==",
- "license": "MIT",
- "dependencies": {
- "colorette": "^2.0.7",
- "dateformat": "^4.6.3",
- "fast-copy": "^3.0.0",
- "fast-safe-stringify": "^2.1.1",
- "help-me": "^5.0.0",
- "joycon": "^3.1.1",
- "minimist": "^1.2.6",
- "on-exit-leak-free": "^2.1.0",
- "pino-abstract-transport": "^1.0.0",
- "pump": "^3.0.0",
- "readable-stream": "^4.0.0",
- "secure-json-parse": "^2.4.0",
- "sonic-boom": "^3.0.0",
- "strip-json-comments": "^3.1.1"
- },
- "bin": {
- "pino-pretty": "bin.js"
- }
- },
- "node_modules/pino-std-serializers": {
- "version": "6.2.2",
- "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-6.2.2.tgz",
- "integrity": "sha512-cHjPPsE+vhj/tnhCy/wiMh3M3z3h/j15zHQX+S9GkTBgqJuTuJzYJ4gUyACLhDaJ7kk9ba9iRDmbH2tJU03OiA==",
- "license": "MIT"
- },
- "node_modules/process": {
- "version": "0.11.10",
- "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
- "integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6.0"
- }
- },
- "node_modules/process-warning": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",
- "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",
- "license": "MIT"
- },
- "node_modules/proxy-addr": {
- "version": "2.0.7",
- "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
- "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
- "license": "MIT",
- "dependencies": {
- "forwarded": "0.2.0",
- "ipaddr.js": "1.9.1"
- },
- "engines": {
- "node": ">= 0.10"
- }
- },
- "node_modules/pump": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz",
- "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==",
- "license": "MIT",
- "dependencies": {
- "end-of-stream": "^1.1.0",
- "once": "^1.3.1"
- }
- },
- "node_modules/quick-format-unescaped": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
- "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",
- "license": "MIT"
- },
- "node_modules/readable-stream": {
- "version": "4.7.0",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
- "integrity": "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==",
- "license": "MIT",
- "dependencies": {
- "abort-controller": "^3.0.0",
- "buffer": "^6.0.3",
- "events": "^3.3.0",
- "process": "^0.11.10",
- "string_decoder": "^1.3.0"
- },
- "engines": {
- "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
- }
- },
- "node_modules/real-require": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
- "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
- "license": "MIT",
- "engines": {
- "node": ">= 12.13.0"
- }
- },
- "node_modules/require-from-string": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
- "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/resolve-pkg-maps": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
- "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
- "dev": true,
- "license": "MIT",
- "funding": {
- "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
- }
- },
- "node_modules/ret": {
- "version": "0.4.3",
- "resolved": "https://registry.npmjs.org/ret/-/ret-0.4.3.tgz",
- "integrity": "sha512-0f4Memo5QP7WQyUEAYUO3esD/XjOc3Zjjg5CPsAq1p8sIu0XPeMbHJemKA0BO7tV0X7+A0FoEpbmHXWxPyD3wQ==",
- "license": "MIT",
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/reusify": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
- "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
- "license": "MIT",
- "engines": {
- "iojs": ">=1.0.0",
- "node": ">=0.10.0"
- }
- },
- "node_modules/rfdc": {
- "version": "1.4.1",
- "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
- "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
- "license": "MIT"
- },
- "node_modules/safe-buffer": {
- "version": "5.2.1",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
- "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/feross"
- },
- {
- "type": "patreon",
- "url": "https://www.patreon.com/feross"
- },
- {
- "type": "consulting",
- "url": "https://feross.org/support"
- }
- ],
- "license": "MIT"
- },
- "node_modules/safe-regex2": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-3.1.0.tgz",
- "integrity": "sha512-RAAZAGbap2kBfbVhvmnTFv73NWLMvDGOITFYTZBAaY8eR+Ir4ef7Up/e7amo+y1+AH+3PtLkrt9mvcTsG9LXug==",
- "license": "MIT",
- "dependencies": {
- "ret": "~0.4.0"
- }
- },
- "node_modules/safe-stable-stringify": {
- "version": "2.5.0",
- "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
- "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
- "license": "MIT",
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/secure-json-parse": {
- "version": "2.7.0",
- "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",
- "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==",
- "license": "BSD-3-Clause"
- },
- "node_modules/semver": {
- "version": "7.7.2",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
- "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
- "license": "ISC",
- "bin": {
- "semver": "bin/semver.js"
- },
- "engines": {
- "node": ">=10"
- }
- },
- "node_modules/set-cookie-parser": {
- "version": "2.7.1",
- "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
- "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
- "license": "MIT"
- },
- "node_modules/sonic-boom": {
- "version": "3.8.1",
- "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.8.1.tgz",
- "integrity": "sha512-y4Z8LCDBuum+PBP3lSV7RHrXscqksve/bi0as7mhwVnBW+/wUqKT/2Kb7um8yqcFy0duYbbPxzt89Zy2nOCaxg==",
- "license": "MIT",
- "dependencies": {
- "atomic-sleep": "^1.0.0"
- }
- },
- "node_modules/split2": {
- "version": "4.2.0",
- "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
- "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
- "license": "ISC",
- "engines": {
- "node": ">= 10.x"
- }
- },
- "node_modules/string_decoder": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
- "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
- "license": "MIT",
- "dependencies": {
- "safe-buffer": "~5.2.0"
- }
- },
- "node_modules/strip-json-comments": {
- "version": "3.1.1",
- "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
- "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/thread-stream": {
- "version": "2.7.0",
- "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-2.7.0.tgz",
- "integrity": "sha512-qQiRWsU/wvNolI6tbbCKd9iKaTnCXsTwVxhhKM6nctPdujTyztjlbUkUTUymidWcMnZ5pWR0ej4a0tjsW021vw==",
- "license": "MIT",
- "dependencies": {
- "real-require": "^0.2.0"
- }
- },
- "node_modules/toad-cache": {
- "version": "3.7.0",
- "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz",
- "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==",
- "license": "MIT",
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/tsx": {
- "version": "4.20.3",
- "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.3.tgz",
- "integrity": "sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "esbuild": "~0.25.0",
- "get-tsconfig": "^4.7.5"
- },
- "bin": {
- "tsx": "dist/cli.mjs"
- },
- "engines": {
- "node": ">=18.0.0"
- },
- "optionalDependencies": {
- "fsevents": "~2.3.3"
- }
- },
- "node_modules/typescript": {
- "version": "5.8.3",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
- "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
- },
- "engines": {
- "node": ">=14.17"
- }
- },
- "node_modules/undici": {
- "version": "6.21.3",
- "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
- "integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
- "license": "MIT",
- "engines": {
- "node": ">=18.17"
- }
- },
- "node_modules/undici-types": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
- "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/wrappy": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "license": "ISC"
- },
- "node_modules/zod": {
- "version": "3.25.76",
- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/colinhacks"
- }
- }
- }
-}
diff --git a/monitor-agent/package.json b/monitor-agent/package.json
deleted file mode 100644
index 5aaceb106..000000000
--- a/monitor-agent/package.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "name": "rybbit-monitor-agent",
- "version": "1.0.0",
- "description": "Regional monitoring agent for Rybbit uptime monitoring",
- "main": "dist/index.js",
- "type": "module",
- "scripts": {
- "dev": "tsx watch src/index.ts",
- "build": "tsc",
- "start": "node dist/index.js",
- "docker:build": "docker build -t monitor-agent .",
- "docker:run": "docker run -p 3000:3000 --env-file .env monitor-agent"
- },
- "dependencies": {
- "fastify": "^4.25.0",
- "@fastify/cors": "^8.5.0",
- "undici": "^6.2.0",
- "dns-packet": "^5.6.1",
- "ping": "^0.4.4",
- "nodemailer": "^6.9.8",
- "pino": "^8.17.0",
- "pino-pretty": "^10.3.0",
- "dotenv": "^16.3.1",
- "zod": "^3.22.4"
- },
- "devDependencies": {
- "@types/node": "^20.10.0",
- "@types/nodemailer": "^6.4.14",
- "@types/ping": "^0.4.4",
- "tsx": "^4.6.0",
- "typescript": "^5.3.0"
- }
-}
\ No newline at end of file
diff --git a/monitor-agent/src/api/auth.ts b/monitor-agent/src/api/auth.ts
deleted file mode 100644
index 8f94ee75e..000000000
--- a/monitor-agent/src/api/auth.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { FastifyRequest, FastifyReply } from 'fastify';
-import { CONFIG } from '../config.js';
-import { logger } from '../utils/logger.js';
-
-export async function authenticateRequest(
- request: FastifyRequest,
- reply: FastifyReply
-): Promise<void> {
- const clientIp = request.ip;
-
- logger.debug({
- clientIp,
- allowedIPs: CONFIG.ALLOWED_IPS,
- allowedIPsLength: CONFIG.ALLOWED_IPS.length,
- rawEnv: process.env.ALLOWED_IPS
- }, 'Checking IP whitelist');
-
- // If no IPs are whitelisted, allow all (with warning)
- if (CONFIG.ALLOWED_IPS.length === 0) {
- logger.debug({ ip: clientIp }, 'No IP whitelist configured, allowing request');
- return;
- }
-
- // Check IP whitelist
- if (!CONFIG.ALLOWED_IPS.includes(clientIp)) {
- logger.warn({
- ip: clientIp,
- allowedIps: CONFIG.ALLOWED_IPS
- }, 'Request from non-whitelisted IP');
-
- return reply.code(403).send({
- error: 'Forbidden',
- message: 'Your IP address is not authorized to access this service'
- });
- }
-
- logger.debug({ ip: clientIp }, 'Request from whitelisted IP');
-}
\ No newline at end of file
diff --git a/monitor-agent/src/api/server.ts b/monitor-agent/src/api/server.ts
deleted file mode 100644
index 07f4fa224..000000000
--- a/monitor-agent/src/api/server.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import Fastify from 'fastify';
-import cors from '@fastify/cors';
-import { CONFIG } from '../config.js';
-import { logger } from '../utils/logger.js';
-import { authenticateRequest } from './auth.js';
-import { ExecuteRequest, ExecuteResponse, HttpCheckResult, TcpCheckResult } from '../types.js';
-import { performHttpCheck } from '../monitors/http.js';
-import { performTcpCheck } from '../monitors/tcp.js';
-import { applyValidationRules } from '../utils/validation.js';
-
-export async function createServer() {
- const fastify = Fastify({
- logger: false, // We use our own logger
- trustProxy: true,
- });
-
- // Register plugins
- await fastify.register(cors, {
- origin: false, // Accept requests from any origin
- });
-
- // Health check endpoint (no auth required)
- fastify.get('/health', async () => {
- return {
- status: 'ok',
- region: CONFIG.REGION,
- timestamp: new Date().toISOString(),
- };
- });
-
- // Metrics endpoint (no auth required)
- fastify.get('/metrics', async (_request, reply) => {
- // TODO: Implement Prometheus metrics
- reply.type('text/plain');
- return '# Metrics endpoint not yet implemented';
- });
-
- // Execute monitoring check
- fastify.post<{ Body: ExecuteRequest }>(
- '/execute',
- {
- preHandler: authenticateRequest,
- schema: {
- body: {
- type: 'object',
- required: ['jobId', 'monitorId', 'monitorType', 'config'],
- properties: {
- jobId: { type: 'string' },
- monitorId: { type: 'number' },
- monitorType: { type: 'string', enum: ['http', 'tcp', 'dns', 'smtp', 'ping'] },
- config: { type: 'object' },
- validationRules: { type: 'array', default: [] },
- },
- },
- },
- },
- async (request, reply) => {
- const { jobId, monitorId, monitorType, config, validationRules } = request.body;
-
- logger.info({ jobId, monitorId, monitorType }, 'Executing monitor check');
-
- try {
- let result;
-
- switch (monitorType) {
- case 'http':
- result = await performHttpCheck(config);
- break;
- case 'tcp':
- result = await performTcpCheck(config);
- break;
- case 'dns':
- // TODO: Implement DNS check
- return reply.code(501).send({ error: 'DNS monitoring not yet implemented' });
- case 'smtp':
- // TODO: Implement SMTP check
- return reply.code(501).send({ error: 'SMTP monitoring not yet implemented' });
- case 'ping':
- // TODO: Implement PING check
- return reply.code(501).send({ error: 'PING monitoring not yet implemented' });
- default:
- return reply.code(400).send({ error: `Unknown monitor type: ${monitorType}` });
- }
-
- // Apply validation rules (only for HTTP checks)
- if (result.status === 'success' && validationRules.length > 0 && monitorType === 'http') {
- const httpResult = result as HttpCheckResult;
- const validationErrors = applyValidationRules(httpResult, validationRules);
- if (validationErrors.length > 0) {
- httpResult.validationErrors = validationErrors;
- httpResult.status = 'failure';
- }
- }
-
- const response: ExecuteResponse = {
- jobId,
- region: CONFIG.REGION,
- status: result.status,
- responseTimeMs: result.responseTimeMs,
- error: result.error,
- };
-
- // Add HTTP-specific fields
- if (monitorType === 'http' && result && 'statusCode' in result) {
- const httpResult = result as HttpCheckResult;
- response.statusCode = httpResult.statusCode;
- response.headers = httpResult.headers;
- response.timing = httpResult.timing;
- response.bodySizeBytes = httpResult.bodySizeBytes;
- response.validationErrors = httpResult.validationErrors;
- }
-
- // Add validation errors for TCP if any
- if (monitorType === 'tcp' && result && 'validationErrors' in result) {
- const tcpResult = result as TcpCheckResult;
- response.validationErrors = tcpResult.validationErrors;
- }
-
- logger.info(
- {
- jobId,
- monitorId,
- status: result.status,
- responseTimeMs: result.responseTimeMs
- },
- 'Monitor check completed'
- );
-
- return response;
-
- } catch (error) {
- logger.error({ error, jobId, monitorId }, 'Monitor check failed with unexpected error');
-
- return {
- jobId,
- region: CONFIG.REGION,
- status: 'failure',
- responseTimeMs: 0,
- error: {
- message: error instanceof Error ? error.message : 'Unknown error',
- type: 'internal_error',
- },
- } as ExecuteResponse;
- }
- }
- );
-
- return fastify;
-}
\ No newline at end of file
diff --git a/monitor-agent/src/config.ts b/monitor-agent/src/config.ts
deleted file mode 100644
index 1cab647c3..000000000
--- a/monitor-agent/src/config.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { config } from "dotenv";
-
-// Load environment variables
-config();
-
-export const CONFIG = {
- // Server configuration
- PORT: parseInt(process.env.PORT || "3003", 10),
- HOST: process.env.HOST || "0.0.0.0",
-
- // Region identifier (e.g., "us-east", "europe", "asia")
- REGION: process.env.REGION || "unknown",
-
- // Security - IP whitelist for main server
- ALLOWED_IPS: process.env.ALLOWED_IPS && process.env.ALLOWED_IPS.trim()
- ? process.env.ALLOWED_IPS.split(",").map((ip) => ip.trim()).filter((ip) => ip.length > 0)
- : [],
-
- // Monitoring defaults
- DEFAULT_TIMEOUT_MS: parseInt(process.env.DEFAULT_TIMEOUT_MS || "30000", 10),
- MAX_TIMEOUT_MS: parseInt(process.env.MAX_TIMEOUT_MS || "60000", 10),
-
- // Logging
- LOG_LEVEL: process.env.LOG_LEVEL || "info",
-};
-
-// Validate required configuration
-export function validateConfig(): void {
- const required = ["REGION"];
- const missing = required.filter((key) => !CONFIG[key as keyof typeof CONFIG]);
-
- if (missing.length > 0) {
- throw new Error(`Missing required environment variables: ${missing.join(", ")}`);
- }
-
- // Warn if no IP whitelist is configured
- if (CONFIG.ALLOWED_IPS.length === 0) {
- console.warn("WARNING: No IP whitelist configured. Agent will accept requests from any IP address.");
- }
-}
diff --git a/monitor-agent/src/index.ts b/monitor-agent/src/index.ts
deleted file mode 100644
index 86e782952..000000000
--- a/monitor-agent/src/index.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { CONFIG, validateConfig } from './config.js';
-import { logger } from './utils/logger.js';
-import { createServer } from './api/server.js';
-
-async function start() {
- try {
- // Validate configuration
- validateConfig();
-
- logger.info(
- {
- region: CONFIG.REGION,
- port: CONFIG.PORT,
- },
- 'Starting monitor agent'
- );
-
- // Create and start server
- const server = await createServer();
-
- await server.listen({
- port: CONFIG.PORT,
- host: CONFIG.HOST,
- });
-
- logger.info(
- {
- region: CONFIG.REGION,
- url: `http://${CONFIG.HOST}:${CONFIG.PORT}`,
- },
- 'Monitor agent started successfully'
- );
-
- // Graceful shutdown
- const shutdown = async (signal: string) => {
- logger.info({ signal }, 'Shutting down monitor agent');
-
- try {
- await server.close();
- logger.info('Monitor agent stopped');
- process.exit(0);
- } catch (error) {
- logger.error({ error }, 'Error during shutdown');
- process.exit(1);
- }
- };
-
- process.on('SIGTERM', () => shutdown('SIGTERM'));
- process.on('SIGINT', () => shutdown('SIGINT'));
-
- } catch (error) {
- logger.fatal({ error }, 'Failed to start monitor agent');
- process.exit(1);
- }
-}
-
-// Start the application
-start();
\ No newline at end of file
diff --git a/monitor-agent/src/monitors/http.ts b/monitor-agent/src/monitors/http.ts
deleted file mode 100644
index f90eaa945..000000000
--- a/monitor-agent/src/monitors/http.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { request } from 'undici';
-import { performance } from 'perf_hooks';
-import dns from 'dns/promises';
-import { MonitorConfig, HttpCheckResult, TimingInfo } from '../types.js';
-import { CONFIG } from '../config.js';
-import { logger } from '../utils/logger.js';
-
-export async function performHttpCheck(config: MonitorConfig): Promise<HttpCheckResult> {
- const startTime = performance.now();
- const timing: TimingInfo = {};
-
- try {
- if (!config.url) {
- throw new Error('URL is required for HTTP monitoring');
- }
-
- const url = new URL(config.url);
-
- // DNS lookup timing
- const dnsStart = performance.now();
- try {
- const dnsOptions: any = {};
- if (config.ipVersion === 'ipv4') dnsOptions.family = 4;
- if (config.ipVersion === 'ipv6') dnsOptions.family = 6;
-
- await dns.lookup(url.hostname, dnsOptions);
- timing.dnsMs = Math.round(performance.now() - dnsStart);
- } catch (dnsError) {
- logger.error({ error: dnsError, hostname: url.hostname }, 'DNS lookup failed');
- throw new Error(`DNS lookup failed: ${dnsError}`);
- }
-
- // Build headers
- const headers: Record<string, string> = {
- 'User-Agent': config.userAgent || 'Rybbit-Monitor/1.0',
- ...config.headers,
- };
-
- // Add authentication
- if (config.auth) {
- switch (config.auth.type) {
- case 'basic':
- if (config.auth.credentials?.username && config.auth.credentials?.password) {
- const basicAuth = Buffer.from(
- `${config.auth.credentials.username}:${config.auth.credentials.password}`
- ).toString('base64');
- headers['Authorization'] = `Basic ${basicAuth}`;
- }
- break;
- case 'bearer':
- if (config.auth.credentials?.token) {
- headers['Authorization'] = `Bearer ${config.auth.credentials.token}`;
- }
- break;
- case 'api_key':
- case 'custom_header':
- if (config.auth.credentials?.headerName && config.auth.credentials?.headerValue) {
- headers[config.auth.credentials.headerName] = config.auth.credentials.headerValue;
- }
- break;
- }
- }
-
- // Perform request
- const requestStart = performance.now();
- const response = await request(config.url, {
- method: (config.method || 'GET') as any,
- headers,
- body: config.body,
- bodyTimeout: Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS),
- headersTimeout: Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS),
- maxRedirections: config.followRedirects !== false ? 5 : 0,
- });
-
- // Calculate timings
- timing.ttfbMs = Math.round(performance.now() - requestStart);
-
- // Get response body and size
- const transferStart = performance.now();
- const bodyBuffer = await response.body.arrayBuffer();
- const bodySizeBytes = bodyBuffer.byteLength;
-
- timing.transferMs = Math.round(performance.now() - transferStart);
-
- // Estimate TCP and TLS times (approximations)
- timing.tcpMs = Math.round((timing.ttfbMs - timing.dnsMs) * 0.3);
- if (url.protocol === 'https:') {
- timing.tlsMs = Math.round((timing.ttfbMs - timing.dnsMs - timing.tcpMs) * 0.5);
- }
-
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- // Convert headers to simple object
- const responseHeaders: Record<string, string> = {};
- for (const [key, value] of Object.entries(response.headers)) {
- responseHeaders[key] = Array.isArray(value) ? value.join(', ') : String(value);
- }
-
- return {
- status: 'success',
- statusCode: response.statusCode,
- responseTimeMs,
- timing,
- headers: responseHeaders,
- bodySizeBytes,
- validationErrors: [],
- };
-
- } catch (error: any) {
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- // Handle different error types
- let errorType = 'unknown_error';
- let errorMessage = error.message || 'Unknown error occurred';
-
- if (error.code === 'UND_ERR_CONNECT_TIMEOUT') {
- errorType = 'connection_timeout';
- errorMessage = 'Connection timed out';
- } else if (error.code === 'UND_ERR_HEADERS_TIMEOUT') {
- errorType = 'headers_timeout';
- errorMessage = 'Headers timeout';
- } else if (error.code === 'UND_ERR_BODY_TIMEOUT') {
- errorType = 'body_timeout';
- errorMessage = 'Body timeout';
- } else if (error.code === 'ENOTFOUND') {
- errorType = 'dns_failure';
- errorMessage = 'DNS lookup failed';
- } else if (error.code === 'ECONNREFUSED') {
- errorType = 'connection_refused';
- errorMessage = 'Connection refused';
- } else if (error.message?.includes('SSL') || error.message?.includes('TLS')) {
- errorType = 'ssl_error';
- }
-
- logger.error({ error, url: config.url }, 'HTTP check failed');
-
- return {
- status: errorType.includes('timeout') ? 'timeout' : 'failure',
- responseTimeMs,
- timing,
- headers: {},
- bodySizeBytes: 0,
- validationErrors: [],
- error: {
- message: errorMessage,
- type: errorType,
- },
- };
- }
-}
\ No newline at end of file
diff --git a/monitor-agent/src/monitors/tcp.ts b/monitor-agent/src/monitors/tcp.ts
deleted file mode 100644
index 09de5caf0..000000000
--- a/monitor-agent/src/monitors/tcp.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import net from 'net';
-import { performance } from 'perf_hooks';
-import { MonitorConfig, TcpCheckResult } from '../types.js';
-import { CONFIG } from '../config.js';
-import { logger } from '../utils/logger.js';
-
-export async function performTcpCheck(config: MonitorConfig): Promise<TcpCheckResult> {
- const startTime = performance.now();
-
- return new Promise((resolve) => {
- if (!config.host || !config.port) {
- resolve({
- status: 'failure',
- responseTimeMs: 0,
- error: {
- message: 'Host and port are required for TCP monitoring',
- type: 'configuration_error',
- },
- });
- return;
- }
-
- const timeout = Math.min(config.timeoutMs || CONFIG.DEFAULT_TIMEOUT_MS, CONFIG.MAX_TIMEOUT_MS);
- const socket = new net.Socket();
-
- // Set timeout
- const timeoutHandle = setTimeout(() => {
- socket.destroy();
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- logger.warn({ host: config.host, port: config.port, responseTimeMs }, 'TCP connection timeout');
-
- resolve({
- status: 'timeout',
- responseTimeMs,
- error: {
- message: 'Connection timeout',
- type: 'timeout',
- },
- });
- }, timeout);
-
- // Handle connection success
- socket.on('connect', () => {
- clearTimeout(timeoutHandle);
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- logger.info({ host: config.host, port: config.port, responseTimeMs }, 'TCP connection successful');
-
- socket.destroy();
- resolve({
- status: 'success',
- responseTimeMs,
- });
- });
-
- // Handle errors
- socket.on('error', (error: any) => {
- clearTimeout(timeoutHandle);
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- let errorType = 'connection_error';
- let errorMessage = error.message;
-
- if (error.code === 'ECONNREFUSED') {
- errorType = 'connection_refused';
- errorMessage = 'Connection refused';
- } else if (error.code === 'EHOSTUNREACH') {
- errorType = 'host_unreachable';
- errorMessage = 'Host unreachable';
- } else if (error.code === 'ENOTFOUND') {
- errorType = 'dns_failure';
- errorMessage = 'Host not found';
- }
-
- logger.error({ error, host: config.host, port: config.port }, 'TCP check failed');
-
- resolve({
- status: 'failure',
- responseTimeMs,
- error: {
- message: errorMessage,
- type: errorType,
- },
- });
- });
-
- // Initiate connection
- socket.connect(config.port, config.host);
- });
-}
\ No newline at end of file
diff --git a/monitor-agent/src/types.ts b/monitor-agent/src/types.ts
deleted file mode 100644
index 3006764cb..000000000
--- a/monitor-agent/src/types.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-export interface MonitorConfig {
- // HTTP config
- url?: string;
- method?: string;
- headers?: Record<string, string>;
- body?: string;
- auth?: {
- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
- credentials?: {
- username?: string;
- password?: string;
- token?: string;
- headerName?: string;
- headerValue?: string;
- };
- };
- followRedirects?: boolean;
- timeoutMs?: number;
- ipVersion?: "any" | "ipv4" | "ipv6";
- userAgent?: string;
-
- // TCP config
- host?: string;
- port?: number;
-
- // DNS config
- hostname?: string;
- recordType?: "A" | "AAAA" | "CNAME" | "MX" | "TXT" | "NS" | "SOA";
- expectedValue?: string;
-
- // SMTP config
- smtpHost?: string;
- smtpPort?: number;
- smtpSecure?: boolean;
- smtpAuth?: {
- user?: string;
- pass?: string;
- };
-}
-
-export interface ValidationRule {
- type: string;
- operator?: string;
- value?: any;
- header?: string;
- caseSensitive?: boolean;
-}
-
-export interface ExecuteRequest {
- jobId: string;
- monitorId: number;
- monitorType: "http" | "tcp" | "dns" | "smtp" | "ping";
- config: MonitorConfig;
- validationRules: ValidationRule[];
-}
-
-export interface TimingInfo {
- dnsMs?: number;
- tcpMs?: number;
- tlsMs?: number;
- ttfbMs?: number;
- transferMs?: number;
-}
-
-export interface ErrorInfo {
- message: string;
- type: string;
-}
-
-export interface ExecuteResponse {
- jobId: string;
- region: string;
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- statusCode?: number;
- headers?: Record<string, string>;
- timing?: TimingInfo;
- error?: ErrorInfo;
- validationErrors?: string[];
- bodySizeBytes?: number;
-}
-
-export interface HttpCheckResult {
- status: "success" | "failure" | "timeout";
- statusCode?: number;
- responseTimeMs: number;
- timing: TimingInfo;
- headers: Record<string, string>;
- bodySizeBytes: number;
- validationErrors: string[];
- error?: ErrorInfo;
-}
-
-export interface TcpCheckResult {
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- validationErrors?: string[];
- error?: ErrorInfo;
-}
-
-export interface DnsCheckResult {
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- answers?: any[];
- error?: ErrorInfo;
-}
-
-export interface SmtpCheckResult {
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- error?: ErrorInfo;
-}
\ No newline at end of file
diff --git a/monitor-agent/src/utils/logger.ts b/monitor-agent/src/utils/logger.ts
deleted file mode 100644
index c40acccc1..000000000
--- a/monitor-agent/src/utils/logger.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import pino from 'pino';
-import { CONFIG } from '../config.js';
-
-export const logger = pino({
- level: CONFIG.LOG_LEVEL,
- transport: {
- target: 'pino-pretty',
- options: {
- colorize: true,
- ignore: 'pid,hostname',
- translateTime: 'HH:MM:ss Z',
- },
- },
- base: {
- region: CONFIG.REGION,
- },
-});
\ No newline at end of file
diff --git a/monitor-agent/src/utils/validation.ts b/monitor-agent/src/utils/validation.ts
deleted file mode 100644
index 8c35627cb..000000000
--- a/monitor-agent/src/utils/validation.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { HttpCheckResult, ValidationRule } from '../types.js';
-
-export function applyValidationRules(
- result: HttpCheckResult,
- rules: ValidationRule[]
-): string[] {
- const errors: string[] = [];
-
- for (const rule of rules) {
- switch (rule.type) {
- case 'status_code':
- if (!validateStatusCode(result.statusCode, rule)) {
- errors.push(
- `Status code validation failed: expected ${rule.operator} ${rule.value}, got ${result.statusCode}`
- );
- }
- break;
-
- case 'response_time':
- if (!validateResponseTime(result.responseTimeMs, rule)) {
- errors.push(
- `Response time validation failed: expected ${rule.operator} ${rule.value}ms, got ${result.responseTimeMs}ms`
- );
- }
- break;
-
- case 'header_exists':
- if (!result.headers[rule.header!]) {
- errors.push(`Required header missing: ${rule.header}`);
- }
- break;
-
- case 'header_value':
- const headerValue = result.headers[rule.header!];
- if (!validateHeaderValue(headerValue, rule)) {
- errors.push(
- `Header ${rule.header} validation failed: expected ${rule.operator} "${rule.value}", got "${headerValue}"`
- );
- }
- break;
-
- case 'response_size':
- if (!validateSize(result.bodySizeBytes, rule)) {
- errors.push(
- `Response size validation failed: expected ${rule.operator} ${rule.value} bytes, got ${result.bodySizeBytes} bytes`
- );
- }
- break;
-
- // Note: response_body_contains validation would require storing the body
- // which we're avoiding for performance reasons
- }
- }
-
- return errors;
-}
-
-function validateStatusCode(statusCode: number | undefined, rule: ValidationRule): boolean {
- if (statusCode === undefined) return false;
-
- switch (rule.operator) {
- case 'equals':
- return statusCode === rule.value;
- case 'not_equals':
- return statusCode !== rule.value;
- case 'in':
- return Array.isArray(rule.value) && rule.value.includes(statusCode);
- case 'not_in':
- return Array.isArray(rule.value) && !rule.value.includes(statusCode);
- default:
- return true;
- }
-}
-
-function validateResponseTime(responseTime: number, rule: ValidationRule): boolean {
- switch (rule.operator) {
- case 'less_than':
- return responseTime < rule.value;
- case 'greater_than':
- return responseTime > rule.value;
- default:
- return true;
- }
-}
-
-function validateHeaderValue(headerValue: string | undefined, rule: ValidationRule): boolean {
- if (!headerValue) return false;
-
- switch (rule.operator) {
- case 'equals':
- return headerValue === rule.value;
- case 'contains':
- return headerValue.includes(rule.value);
- default:
- return true;
- }
-}
-
-function validateSize(size: number, rule: ValidationRule): boolean {
- switch (rule.operator) {
- case 'less_than':
- return size < rule.value;
- case 'greater_than':
- return size > rule.value;
- default:
- return true;
- }
-}
\ No newline at end of file
diff --git a/monitor-agent/systemd/rybbit-monitor-agent.service b/monitor-agent/systemd/rybbit-monitor-agent.service
deleted file mode 100644
index 85041134e..000000000
--- a/monitor-agent/systemd/rybbit-monitor-agent.service
+++ /dev/null
@@ -1,37 +0,0 @@
-[Unit]
-Description=Rybbit Monitor Agent
-Documentation=https://github.com/rybbit/monitor-agent
-After=network.target
-
-[Service]
-Type=simple
-User=rybbit
-Group=rybbit
-WorkingDirectory=/opt/rybbit-monitor-agent
-ExecStart=/usr/bin/node /opt/rybbit-monitor-agent/dist/index.js
-Restart=always
-RestartSec=10
-
-# Environment
-Environment="NODE_ENV=production"
-EnvironmentFile=/opt/rybbit-monitor-agent/.env
-
-# Security
-NoNewPrivileges=true
-PrivateTmp=true
-ProtectSystem=strict
-ProtectHome=true
-ReadWritePaths=/opt/rybbit-monitor-agent/logs
-
-# Resource limits
-LimitNOFILE=65536
-MemoryLimit=1G
-CPUQuota=100%
-
-# Logging
-StandardOutput=journal
-StandardError=journal
-SyslogIdentifier=rybbit-monitor-agent
-
-[Install]
-WantedBy=multi-user.target
\ No newline at end of file
diff --git a/monitor-agent/systemd/setup.sh b/monitor-agent/systemd/setup.sh
deleted file mode 100755
index ebbf20948..000000000
--- a/monitor-agent/systemd/setup.sh
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/bin/bash
-
-# Setup script for Rybbit Monitor Agent with systemd
-# Run with sudo: sudo ./setup.sh
-
-set -e
-
-# Colors
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
-RED='\033[0;31m'
-NC='\033[0m'
-
-# Configuration
-INSTALL_DIR="/opt/rybbit-monitor-agent"
-SERVICE_USER="rybbit"
-SERVICE_NAME="rybbit-monitor-agent"
-NODE_VERSION="20"
-
-# Functions
-log_info() {
- echo -e "${GREEN}[INFO]${NC} $1"
-}
-
-log_warn() {
- echo -e "${YELLOW}[WARN]${NC} $1"
-}
-
-log_error() {
- echo -e "${RED}[ERROR]${NC} $1"
-}
-
-# Check if running as root
-if [[ $EUID -ne 0 ]]; then
- log_error "This script must be run as root"
- exit 1
-fi
-
-# Create service user
-if ! id "$SERVICE_USER" &>/dev/null; then
- log_info "Creating service user: $SERVICE_USER"
- useradd --system --shell /bin/false --home-dir "$INSTALL_DIR" "$SERVICE_USER"
-else
- log_info "Service user already exists: $SERVICE_USER"
-fi
-
-# Create installation directory
-log_info "Creating installation directory: $INSTALL_DIR"
-mkdir -p "$INSTALL_DIR"/{logs,dist}
-
-# Check Node.js installation
-if ! command -v node &> /dev/null; then
- log_error "Node.js is not installed. Please install Node.js $NODE_VERSION or later"
- exit 1
-fi
-
-NODE_MAJOR_VERSION=$(node -v | cut -d. -f1 | sed 's/v//')
-if [[ $NODE_MAJOR_VERSION -lt $NODE_VERSION ]]; then
- log_error "Node.js version $NODE_VERSION or later is required. Current version: $(node -v)"
- exit 1
-fi
-
-# Copy application files
-log_info "Copying application files..."
-cp -r ../dist/* "$INSTALL_DIR/dist/"
-cp ../package.json "$INSTALL_DIR/"
-
-# Install production dependencies
-log_info "Installing production dependencies..."
-cd "$INSTALL_DIR"
-npm ci --production
-
-# Create environment file if it doesn't exist
-if [[ ! -f "$INSTALL_DIR/.env" ]]; then
- log_info "Creating environment file..."
- cat > "$INSTALL_DIR/.env" << EOF
-# Rybbit Monitor Agent Configuration
-NODE_ENV=production
-PORT=3000
-HOST=0.0.0.0
-
-# Region Configuration
-REGION=${REGION:-us-east}
-REGION_NAME=${REGION_NAME:-US East}
-
-# Main Server
-MAIN_SERVER_URL=https://your-rybbit-server.com
-
-# Security - IP Whitelist (comma-separated)
-# Leave empty to allow all IPs (not recommended for production)
-ALLOWED_IPS=
-
-# Monitoring Settings
-DEFAULT_TIMEOUT_MS=30000
-MAX_TIMEOUT_MS=60000
-
-# Logging
-LOG_LEVEL=info
-
-# Health Check
-HEALTH_CHECK_INTERVAL_MS=30000
-EOF
- log_warn "Please edit $INSTALL_DIR/.env with your configuration"
-fi
-
-# Set proper permissions
-log_info "Setting permissions..."
-chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"
-chmod 600 "$INSTALL_DIR/.env"
-
-# Install systemd service
-log_info "Installing systemd service..."
-cp rybbit-monitor-agent.service /etc/systemd/system/
-systemctl daemon-reload
-
-# Enable and start service
-log_info "Enabling service..."
-systemctl enable "$SERVICE_NAME"
-
-log_info "Starting service..."
-systemctl start "$SERVICE_NAME"
-
-# Check service status
-sleep 2
-if systemctl is-active --quiet "$SERVICE_NAME"; then
- log_info "Service started successfully!"
- systemctl status "$SERVICE_NAME" --no-pager
-else
- log_error "Service failed to start"
- journalctl -u "$SERVICE_NAME" -n 50 --no-pager
- exit 1
-fi
-
-# Setup log rotation
-log_info "Setting up log rotation..."
-cat > /etc/logrotate.d/rybbit-monitor-agent << EOF
-$INSTALL_DIR/logs/*.log {
- daily
- rotate 14
- compress
- delaycompress
- missingok
- notifempty
- create 0640 $SERVICE_USER $SERVICE_USER
- sharedscripts
- postrotate
- systemctl reload $SERVICE_NAME > /dev/null 2>&1 || true
- endscript
-}
-EOF
-
-# Setup firewall (if ufw is installed)
-if command -v ufw &> /dev/null; then
- log_info "Configuring firewall..."
- ufw allow 3000/tcp comment "Rybbit Monitor Agent"
-fi
-
-log_info "Installation complete!"
-log_info ""
-log_info "Next steps:"
-log_info "1. Edit the configuration file: $INSTALL_DIR/.env"
-log_info "2. Add IP whitelist for your main server"
-log_info "3. Restart the service: systemctl restart $SERVICE_NAME"
-log_info "4. Check logs: journalctl -u $SERVICE_NAME -f"
-log_info ""
-log_info "Service management commands:"
-log_info " Start: systemctl start $SERVICE_NAME"
-log_info " Stop: systemctl stop $SERVICE_NAME"
-log_info " Restart: systemctl restart $SERVICE_NAME"
-log_info " Status: systemctl status $SERVICE_NAME"
-log_info " Logs: journalctl -u $SERVICE_NAME -f"
\ No newline at end of file
diff --git a/monitor-agent/tsconfig.json b/monitor-agent/tsconfig.json
deleted file mode 100644
index 9dbc68b9b..000000000
--- a/monitor-agent/tsconfig.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "ES2022",
- "lib": ["ES2022"],
- "moduleResolution": "node",
- "outDir": "./dist",
- "rootDir": "./src",
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true,
- "allowJs": true,
- "noEmit": false,
- "declaration": true,
- "declarationMap": true,
- "sourceMap": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true,
- "noUncheckedIndexedAccess": true,
- "allowSyntheticDefaultImports": true,
- "typeRoots": ["./node_modules/@types"]
- },
- "include": ["src/**/*"],
- "exclude": ["node_modules", "dist"]
-}
\ No newline at end of file
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 3e3dbbeba..83d202d1d 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -28,7 +28,7 @@ Do not run database migration, push, pull, or drop commands unless the user expl
- Drizzle ORM with Postgres for relational data.
- ClickHouse for analytics event storage and querying.
- Zod for request validation.
-- BullMQ, cron jobs, and service classes for background work.
+- Cron jobs and service classes for background work.
- Vitest for tests.
- Pino via Fastify logger for logging.
@@ -39,13 +39,12 @@ Do not run database migration, push, pull, or drop commands unless the user expl
- `src/api/` - route handlers grouped by domain.
- `src/api/analytics/` - analytics query endpoints.
- `src/api/sites/` - site management, imports, tracking config, and script verification.
-- `src/api/uptime/` - uptime monitor endpoints.
- `src/api/user/`, `src/api/teams/`, `src/api/memberAccess/` - account, organization, team, and access APIs.
- `src/api/stripe/` - billing and Stripe webhook handlers.
- `src/db/postgres/` - Drizzle schema, client setup, and Postgres helpers.
- `src/db/clickhouse/` - ClickHouse client, migrations, and analytics storage helpers.
- `src/lib/` - auth middleware, auth utilities, constants, logger helpers, and shared server utilities.
-- `src/services/` - domain services for tracking, sessions, replay, uptime, imports, reporting, storage, and email.
+- `src/services/` - domain services for tracking, sessions, replay, imports, reporting, storage, and email.
- `src/analytics-script/` - browser analytics script source and build tooling.
- `drizzle/` - generated SQL migration files.
- `public/` - served browser assets such as tracking and replay scripts.
diff --git a/server/drizzle/0014_huge_dagger.sql b/server/drizzle/0014_huge_dagger.sql
new file mode 100644
index 000000000..7a4443858
--- /dev/null
+++ b/server/drizzle/0014_huge_dagger.sql
@@ -0,0 +1,12 @@
+-- Drops the uptime monitoring tables. Every foreign key into this set comes from
+-- another table in the set, and the generated order already lists dependents
+-- before their parents, so CASCADE is not needed. Leaving CASCADE off means an
+-- undeclared dependent (a view, or a foreign key added outside this schema)
+-- aborts the migration instead of being silently dropped along with the table.
+DROP TABLE IF EXISTS "agent_regions";--> statement-breakpoint
+DROP TABLE IF EXISTS "notification_channels";--> statement-breakpoint
+DROP TABLE IF EXISTS "uptime_alert_history";--> statement-breakpoint
+DROP TABLE IF EXISTS "uptime_alerts";--> statement-breakpoint
+DROP TABLE IF EXISTS "uptime_incidents";--> statement-breakpoint
+DROP TABLE IF EXISTS "uptime_monitor_status";--> statement-breakpoint
+DROP TABLE IF EXISTS "uptime_monitors";
diff --git a/server/drizzle/meta/0014_snapshot.json b/server/drizzle/meta/0014_snapshot.json
new file mode 100644
index 000000000..f334aff3b
--- /dev/null
+++ b/server/drizzle/meta/0014_snapshot.json
@@ -0,0 +1,2936 @@
+{
+ "id": "f1e9d929-9eb0-4d14-9a41-037b634844fe",
+ "prevId": "0e3a4617-e367-41a6-b4e5-402ac9f78f16",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json
index 3b232a627..fa3614a33 100644
--- a/server/drizzle/meta/_journal.json
+++ b/server/drizzle/meta/_journal.json
@@ -99,6 +99,13 @@
"when": 1784659838680,
"tag": "0013_square_bloodaxe",
"breakpoints": true
+ },
+ {
+ "idx": 14,
+ "version": "7",
+ "when": 1786751242462,
+ "tag": "0014_huge_dagger",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/server/package.json b/server/package.json
index a1dd56c67..f587fe217 100644
--- a/server/package.json
+++ b/server/package.json
@@ -21,7 +21,6 @@
"db:drop": "drizzle-kit drop --config=drizzle.config.ts",
"db:check": "drizzle-kit check --config=drizzle.config.ts",
"update:datacenter-asns": "node src/services/tracker/botBlocking/update-datacenter-asns.mjs",
- "update:referrer-spam": "node src/services/tracker/botBlocking/update-referrer-spam.mjs",
"knip": "knip",
"format": "prettier --write \"src/**/*.{js,ts,json,md}\"",
"format:check": "prettier --check \"src/**/*.{js,ts,json,md}\"",
@@ -44,7 +43,6 @@
"@react-email/tailwind": "2.0.1",
"@rybbit/shared": "file:../shared",
"better-auth": "1.6.25",
- "bullmq": "^5.56.5",
"dotenv": "16.5.0",
"drizzle-orm": "0.45.2",
"fastify": "5.8.5",
@@ -67,9 +65,7 @@
"safe-regex2": "^5.0.0",
"sqlstring": "2.3.3",
"stripe": "18.1.0",
- "twilio": "^5.8.0",
"ua-parser-js": "2.0.3",
- "undici": "^7.9.0",
"web-vitals": "^5.0.3",
"zod": "^3.25.76"
},
diff --git a/server/src/api/admin/getClickhouseStats.ts b/server/src/api/admin/getClickhouseStats.ts
index d656f8178..d7b0ccd28 100644
--- a/server/src/api/admin/getClickhouseStats.ts
+++ b/server/src/api/admin/getClickhouseStats.ts
@@ -50,7 +50,7 @@ export async function getClickhouseStats(request: FastifyRequest<{ Querystring:
count() as parts_count
FROM system.parts
WHERE database = currentDatabase() AND active = 1
- AND table IN ('events', 'session_replay_events', 'session_replay_metadata', 'monitor_events')
+ AND table IN ('events', 'session_replay_events', 'session_replay_metadata')
GROUP BY table
ORDER BY total_rows DESC
`,
diff --git a/server/src/api/uptime/createMonitor.ts b/server/src/api/uptime/createMonitor.ts
deleted file mode 100644
index 1b842c2e5..000000000
--- a/server/src/api/uptime/createMonitor.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { uptimeService } from "../../services/uptime/uptimeService.js";
-import { createMonitorSchema, type CreateMonitorInput } from "./schemas.js";
-
-interface CreateMonitorBody {
- Body: CreateMonitorInput;
-}
-
-export async function createMonitor(request: FastifyRequest<CreateMonitorBody>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // Validate request body with Zod
- const validatedBody = createMonitorSchema.parse(request.body);
-
- const {
- organizationId,
- name,
- monitorType,
- intervalSeconds,
- enabled,
- httpConfig,
- tcpConfig,
- validationRules,
- monitoringType,
- selectedRegions,
- } = validatedBody;
-
- // Check if user has access to the organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied to organization" });
- }
-
- // Create the monitor
- const [newMonitor] = await db
- .insert(uptimeMonitors)
- .values({
- organizationId,
- name,
- monitorType,
- intervalSeconds,
- enabled,
- httpConfig: monitorType === "http" ? httpConfig : null,
- tcpConfig: monitorType === "tcp" ? tcpConfig : null,
- validationRules,
- monitoringType: monitoringType || "local",
- selectedRegions: selectedRegions || ["local"],
- createdBy: userId,
- })
- .returning();
-
- // Initialize monitor status
- await db.insert(uptimeMonitorStatus).values({
- monitorId: newMonitor.id,
- currentStatus: "unknown",
- consecutiveFailures: 0,
- consecutiveSuccesses: 0,
- });
-
- // Schedule the monitor if enabled
- if (enabled) {
- await uptimeService.onMonitorCreated(newMonitor.id, intervalSeconds);
- }
-
- return reply.status(201).send(newMonitor);
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error creating monitor");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/deleteMonitor.ts b/server/src/api/uptime/deleteMonitor.ts
deleted file mode 100644
index c16db01bc..000000000
--- a/server/src/api/uptime/deleteMonitor.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { uptimeService } from "../../services/uptime/uptimeService.js";
-
-interface DeleteMonitorParams {
- Params: {
- monitorId: string;
- };
-}
-
-export async function deleteMonitor(request: FastifyRequest<DeleteMonitorParams>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // First get the monitor to check if it exists and user has access
- const existingMonitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!existingMonitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, existingMonitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Remove the monitor from the scheduler first
- await uptimeService.onMonitorDeleted(Number(monitorId));
-
- // Delete monitor and related records in a transaction
- await db.transaction(async tx => {
- // Delete monitor status first
- await tx.delete(uptimeMonitorStatus).where(eq(uptimeMonitorStatus.monitorId, Number(monitorId)));
-
- // Delete the monitor
- await tx.delete(uptimeMonitors).where(eq(uptimeMonitors.id, Number(monitorId)));
- });
-
- return reply.status(204).send();
- } catch (error) {
- request.log.error({ err: error }, "Error deleting monitor");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitor.ts b/server/src/api/uptime/getMonitor.ts
deleted file mode 100644
index 148313820..000000000
--- a/server/src/api/uptime/getMonitor.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-
-interface GetMonitorParams {
- Params: {
- monitorId: string;
- };
-}
-
-export async function getMonitor(request: FastifyRequest<GetMonitorParams>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // First get the monitor
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Get monitor with status
- const result = await db
- .select({
- monitor: uptimeMonitors,
- status: uptimeMonitorStatus,
- })
- .from(uptimeMonitors)
- .leftJoin(uptimeMonitorStatus, eq(uptimeMonitors.id, uptimeMonitorStatus.monitorId))
- .where(eq(uptimeMonitors.id, Number(monitorId)))
- .limit(1);
-
- const monitorWithStatus = {
- ...result[0].monitor,
- status: result[0].status,
- };
-
- return reply.status(200).send(monitorWithStatus);
- } catch (error) {
- request.log.error({ err: error }, "Error retrieving monitor");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitorEvents.ts b/server/src/api/uptime/getMonitorEvents.ts
deleted file mode 100644
index a385c2cef..000000000
--- a/server/src/api/uptime/getMonitorEvents.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, member } from "../../db/postgres/schema.js";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults } from "../analytics/utils/utils.js";
-import { getMonitorEventsQuerySchema, type GetMonitorEventsQuery } from "./schemas.js";
-
-interface GetMonitorEventsRequest {
- Params: {
- monitorId: string;
- };
- Querystring: GetMonitorEventsQuery;
-}
-
-export async function getMonitorEvents(request: FastifyRequest<GetMonitorEventsRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // Validate query parameters with Zod
- const query = getMonitorEventsQuerySchema.parse(request.query);
- const { status, region, limit, offset } = query;
- // First check if monitor exists and user has access
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Build query for ClickHouse
- let queryStr = `
- SELECT
- monitor_id,
- organization_id,
- timestamp,
- monitor_type,
- monitor_url,
- monitor_name,
- region,
- status,
- status_code,
- response_time_ms,
- dns_time_ms,
- tcp_time_ms,
- tls_time_ms,
- ttfb_ms,
- transfer_time_ms,
- validation_errors,
- response_headers,
- response_size_bytes,
- port,
- error_message,
- error_type
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- `;
-
- const queryParams: any = { monitorId: Number(monitorId) };
-
- if (status) {
- queryStr += ` AND status = {status: String}`;
- queryParams.status = status;
- }
-
- if (region) {
- queryStr += ` AND region = {region: String}`;
- queryParams.region = region;
- }
-
- queryStr += ` ORDER BY timestamp DESC`;
- queryStr += ` LIMIT {limit: UInt32} OFFSET {offset: UInt32}`;
- queryParams.limit = limit;
- queryParams.offset = offset;
-
- const result = await clickhouse.query({
- query: queryStr,
- query_params: queryParams,
- format: "JSONEachRow",
- });
-
- const events = await processResults(result);
-
- // Get total count
- let countQuery = `
- SELECT count() as total
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- `;
-
- const countParams: any = { monitorId: Number(monitorId) };
-
- if (status) {
- countQuery += ` AND status = {status: String}`;
- countParams.status = status;
- }
-
- if (region) {
- countQuery += ` AND region = {region: String}`;
- countParams.region = region;
- }
-
- const countResult = await clickhouse.query({
- query: countQuery,
- query_params: countParams,
- format: "JSONEachRow",
- });
-
- const countData = await processResults<{ total: number }>(countResult);
- const total = countData[0]?.total || 0;
-
- return reply.status(200).send({
- events,
- pagination: {
- total: Number(total),
- limit: limit,
- offset: offset,
- },
- });
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error retrieving monitor events");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitorStats.ts b/server/src/api/uptime/getMonitorStats.ts
deleted file mode 100644
index 1868d3b8a..000000000
--- a/server/src/api/uptime/getMonitorStats.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { db } from "../../db/postgres/postgres.js";
-import { member, uptimeMonitors } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults, TimeBucketToFn } from "../analytics/utils/utils.js";
-import { getMonitorStatsQuerySchema, type GetMonitorStatsQuery } from "./schemas.js";
-import { DateTime } from "luxon";
-
-interface GetMonitorStatsRequest {
- Params: {
- monitorId: string;
- };
- Querystring: GetMonitorStatsQuery;
-}
-
-export async function getMonitorStats(request: FastifyRequest<GetMonitorStatsRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // Validate query parameters with Zod
- const query = getMonitorStatsQuerySchema.parse(request.query);
- const { region, hours } = query;
- // First check if monitor exists and user has access
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Get aggregated stats from ClickHouse
- let statsQuery = `
- SELECT
- count() as total_checks,
- countIf(status = 'success') as successful_checks,
- countIf(status = 'failure') as failed_checks,
- countIf(status = 'timeout') as timeout_checks,
- avg(response_time_ms) as avg_response_time,
- min(response_time_ms) as min_response_time,
- max(response_time_ms) as max_response_time,
- quantile(0.5)(response_time_ms) as p50_response_time,
- quantile(0.75)(response_time_ms) as p75_response_time,
- quantile(0.90)(response_time_ms) as p90_response_time,
- quantile(0.95)(response_time_ms) as p95_response_time,
- quantile(0.99)(response_time_ms) as p99_response_time,
- 100 * countIf(status = 'success') / count() as uptime_percentage
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- AND timestamp >= now() - INTERVAL {hours: UInt32} HOUR
- `;
-
- const queryParams: any = {
- monitorId: Number(monitorId),
- hours: hours || 24,
- };
-
- if (region) {
- statsQuery += ` AND region = {region: String}`;
- queryParams.region = region;
- }
-
- const statsResult = await clickhouse.query({
- query: statsQuery,
- query_params: queryParams,
- format: "JSONEachRow",
- });
-
- const statsData = await processResults<{
- total_checks: number;
- successful_checks: number;
- failed_checks: number;
- timeout_checks: number;
- avg_response_time: number;
- min_response_time: number;
- max_response_time: number;
- p50_response_time: number;
- p75_response_time: number;
- p90_response_time: number;
- p95_response_time: number;
- p99_response_time: number;
- uptime_percentage: number;
- }>(statsResult);
- const stats = statsData[0] || {
- total_checks: 0,
- successful_checks: 0,
- failed_checks: 0,
- timeout_checks: 0,
- avg_response_time: 0,
- min_response_time: 0,
- max_response_time: 0,
- p50_response_time: 0,
- p75_response_time: 0,
- p90_response_time: 0,
- p95_response_time: 0,
- p99_response_time: 0,
- uptime_percentage: 0,
- };
-
- // Determine time bucket based on time range and interval
- const hoursBack = hours || 24;
- const days = hoursBack / 24;
-
- let bucket = query.bucket || "hour"; // Default to hour if not specified
- if (!query.bucket) {
- // Auto-select bucket based on time range
- if (days <= 1) {
- bucket = "minute";
- } else if (days <= 3) {
- bucket = "five_minutes";
- } else if (days <= 7) {
- bucket = "ten_minutes";
- } else if (days <= 60) {
- bucket = "hour";
- } else {
- bucket = "day";
- }
- }
-
- // Validate bucket is in TimeBucketToFn
- const bucketFn = TimeBucketToFn[bucket as keyof typeof TimeBucketToFn] || TimeBucketToFn.hour;
-
- // Get response time distribution
- let distributionQuery = `
- SELECT
- ${bucketFn}(timestamp) as time_bucket,
- avg(response_time_ms) as avg_response_time,
- avg(dns_time_ms) as avg_dns_time,
- avg(tcp_time_ms) as avg_tcp_time,
- avg(tls_time_ms) as avg_tls_time,
- avg(ttfb_ms) as avg_ttfb,
- avg(transfer_time_ms) as avg_transfer_time,
- count() as check_count,
- countIf(status = 'success') as success_count,
- countIf(status = 'failure') as failure_count,
- countIf(status = 'timeout') as timeout_count
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- AND timestamp >= now() - INTERVAL {hours: UInt32} HOUR
- `;
-
- if (region) {
- distributionQuery += ` AND region = {region: String}`;
- }
-
- distributionQuery += `
- GROUP BY time_bucket
- ORDER BY time_bucket ASC
- `;
-
- const distributionResult = await clickhouse.query({
- query: distributionQuery,
- query_params: queryParams,
- format: "JSONEachRow",
- });
-
- const distribution = await processResults(distributionResult);
-
- // Rename time_bucket back to hour for backward compatibility with frontend
- const formattedDistribution = distribution.map((item: any) => ({
- ...item,
- hour: item.time_bucket,
- }));
-
- return reply.status(200).send({
- hours: hours || 24, // Return the hours used
- region,
- stats: {
- totalChecks: Number(stats.total_checks),
- successfulChecks: Number(stats.successful_checks),
- failedChecks: Number(stats.failed_checks),
- timeoutChecks: Number(stats.timeout_checks),
- uptimePercentage: Number(stats.uptime_percentage),
- responseTime: {
- avg: Number(stats.avg_response_time),
- min: Number(stats.min_response_time),
- max: Number(stats.max_response_time),
- p50: Number(stats.p50_response_time),
- p75: Number(stats.p75_response_time),
- p90: Number(stats.p90_response_time),
- p95: Number(stats.p95_response_time),
- p99: Number(stats.p99_response_time),
- },
- },
- distribution: formattedDistribution,
- monitorType: monitor.monitorType,
- bucket,
- });
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error retrieving monitor stats");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitorStatus.ts b/server/src/api/uptime/getMonitorStatus.ts
deleted file mode 100644
index 0044e4adc..000000000
--- a/server/src/api/uptime/getMonitorStatus.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults } from "../analytics/utils/utils.js";
-
-interface GetMonitorStatusRequest {
- Params: {
- monitorId: string;
- };
-}
-
-export async function getMonitorStatus(request: FastifyRequest<GetMonitorStatusRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // First check if monitor exists and user has access
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Get current status from PostgreSQL
- const currentStatus = await db.query.uptimeMonitorStatus.findFirst({
- where: eq(uptimeMonitorStatus.monitorId, Number(monitorId)),
- });
-
- // Get recent incidents from ClickHouse
- const incidentsQuery = `
- WITH incidents AS (
- SELECT
- timestamp,
- status,
- error_message,
- error_type,
- response_time_ms,
- status_code,
- LAG(status) OVER (ORDER BY timestamp) as prev_status,
- LEAD(status) OVER (ORDER BY timestamp) as next_status
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- AND timestamp >= now() - INTERVAL 7 DAY
- ORDER BY timestamp DESC
- )
- SELECT
- timestamp as incident_start,
- status,
- error_message,
- error_type,
- response_time_ms,
- status_code,
- CASE
- WHEN next_status = 'success' THEN
- LEAD(timestamp) OVER (ORDER BY timestamp)
- ELSE NULL
- END as incident_end
- FROM incidents
- WHERE status != 'success'
- AND (prev_status = 'success' OR prev_status IS NULL)
- ORDER BY timestamp DESC
- LIMIT 10
- `;
-
- const incidentsResult = await clickhouse.query({
- query: incidentsQuery,
- query_params: {
- monitorId: Number(monitorId),
- },
- format: "JSONEachRow",
- });
-
- const recentIncidents = await processResults(incidentsResult);
-
- // Get last 5 checks
- const recentChecksQuery = `
- SELECT
- timestamp,
- status,
- response_time_ms,
- status_code,
- error_message,
- validation_errors
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- ORDER BY timestamp DESC
- LIMIT 5
- `;
-
- const recentChecksResult = await clickhouse.query({
- query: recentChecksQuery,
- query_params: {
- monitorId: Number(monitorId),
- },
- format: "JSONEachRow",
- });
-
- const recentChecks = await processResults(recentChecksResult);
-
- return reply.status(200).send({
- monitorId: Number(monitorId),
- currentStatus: currentStatus || {
- currentStatus: "unknown",
- lastCheckedAt: null,
- nextCheckAt: null,
- consecutiveFailures: 0,
- consecutiveSuccesses: 0,
- },
- recentIncidents,
- recentChecks,
- });
- } catch (error) {
- request.log.error({ err: error }, "Error retrieving monitor status");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitorUptime.ts b/server/src/api/uptime/getMonitorUptime.ts
deleted file mode 100644
index 9951c18bb..000000000
--- a/server/src/api/uptime/getMonitorUptime.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, member } from "../../db/postgres/schema.js";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults } from "../analytics/utils/utils.js";
-
-interface GetMonitorUptimeRequest {
- Params: {
- monitorId: string;
- };
-}
-
-export async function getMonitorUptime(request: FastifyRequest<GetMonitorUptimeRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // First check if monitor exists and user has access
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Get the first check event to determine when monitoring started
- const firstCheckQuery = `
- SELECT
- min(timestamp) as first_check,
- max(timestamp) as last_check
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- `;
-
- const firstCheckResult = await clickhouse.query({
- query: firstCheckQuery,
- query_params: {
- monitorId: Number(monitorId),
- },
- format: "JSONEachRow",
- });
-
- const firstCheckData = await processResults<{
- first_check: string;
- last_check: string;
- }>(firstCheckResult);
-
- if (!firstCheckData[0]?.first_check) {
- return reply.status(200).send({
- monitorId: Number(monitorId),
- totalUptimeSeconds: 0,
- currentUptimeSeconds: 0,
- lastDowntime: null,
- monitoringSince: null,
- lastCheck: null,
- });
- }
-
- const { first_check, last_check } = firstCheckData[0];
-
- // Get the most recent downtime event
- const lastDowntimeQuery = `
- SELECT
- timestamp as downtime_start,
- error_message,
- error_type,
- status
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- AND status != 'success'
- ORDER BY timestamp DESC
- LIMIT 1
- `;
-
- const lastDowntimeResult = await clickhouse.query({
- query: lastDowntimeQuery,
- query_params: {
- monitorId: Number(monitorId),
- },
- format: "JSONEachRow",
- });
-
- const lastDowntimeData = await processResults<{
- downtime_start: string;
- error_message?: string;
- error_type?: string;
- status: string;
- }>(lastDowntimeResult);
-
- const lastDowntime = lastDowntimeData[0] || null;
-
- // Calculate total monitoring duration
- const monitoringStartMs = new Date(first_check).getTime();
- const lastCheckMs = new Date(last_check).getTime();
- const totalMonitoringSeconds = Math.floor((lastCheckMs - monitoringStartMs) / 1000);
-
- // Calculate current uptime (time since last downtime or since monitoring started)
- let currentUptimeSeconds = totalMonitoringSeconds;
- if (lastDowntime) {
- const lastDowntimeMs = new Date(lastDowntime.downtime_start).getTime();
- // Only count as current uptime if the downtime was after monitoring started
- if (lastDowntimeMs > monitoringStartMs) {
- currentUptimeSeconds = Math.floor((lastCheckMs - lastDowntimeMs) / 1000);
- }
- }
-
- // Get total downtime duration for accurate total uptime calculation
- const downtimeStatsQuery = `
- SELECT
- countIf(status != 'success') as total_downtime_checks,
- countIf(status = 'success') as total_uptime_checks,
- count() as total_checks,
- avg(if(status = 'success', 0, 1)) * 100 as downtime_percentage
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- `;
-
- const downtimeStatsResult = await clickhouse.query({
- query: downtimeStatsQuery,
- query_params: {
- monitorId: Number(monitorId),
- },
- format: "JSONEachRow",
- });
-
- const downtimeStats = await processResults<{
- total_downtime_checks: number;
- total_uptime_checks: number;
- total_checks: number;
- downtime_percentage: number;
- }>(downtimeStatsResult);
-
- const stats = downtimeStats[0] || {
- total_downtime_checks: 0,
- total_uptime_checks: 0,
- total_checks: 0,
- downtime_percentage: 0,
- };
-
- // Calculate estimated total uptime based on check intervals
- // This is an approximation since we don't store exact downtime durations
- const avgCheckInterval = monitor.intervalSeconds;
- const estimatedTotalDowntimeSeconds = stats.total_downtime_checks * avgCheckInterval;
- const estimatedTotalUptimeSeconds = Math.max(0, totalMonitoringSeconds - estimatedTotalDowntimeSeconds);
-
- return reply.status(200).send({
- monitorId: Number(monitorId),
- totalUptimeSeconds: estimatedTotalUptimeSeconds,
- currentUptimeSeconds,
- totalMonitoringSeconds,
- lastDowntime: lastDowntime
- ? {
- timestamp: lastDowntime.downtime_start,
- error: lastDowntime.error_message,
- errorType: lastDowntime.error_type,
- status: lastDowntime.status,
- }
- : null,
- monitoringSince: first_check,
- lastCheck: last_check,
- uptimePercentage: 100 - stats.downtime_percentage,
- totalChecks: stats.total_checks,
- failedChecks: stats.total_downtime_checks,
- });
- } catch (error) {
- request.log.error({ err: error }, "Error retrieving monitor uptime");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitorUptimeBuckets.ts b/server/src/api/uptime/getMonitorUptimeBuckets.ts
deleted file mode 100644
index 3703e9a34..000000000
--- a/server/src/api/uptime/getMonitorUptimeBuckets.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { z } from "zod";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { db } from "../../db/postgres/postgres.js";
-import { member, uptimeMonitors } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults } from "../analytics/utils/utils.js";
-
-// Query params schema
-const getMonitorUptimeBucketsQuerySchema = z.object({
- bucket: z.enum(["hour", "day", "week"]).default("day"),
- days: z.string().transform(Number).pipe(z.number().int().positive().max(90)).default("7"),
- timeZone: z.string().optional(),
-});
-
-interface GetMonitorUptimeBucketsRequest {
- Params: {
- monitorId: string;
- };
- Querystring: z.infer<typeof getMonitorUptimeBucketsQuerySchema>;
-}
-
-export async function getMonitorUptimeBuckets(
- request: FastifyRequest<GetMonitorUptimeBucketsRequest>,
- reply: FastifyReply
-) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // Validate query parameters
- const query = getMonitorUptimeBucketsQuerySchema.parse(request.query);
- const { bucket, days, timeZone = "UTC" } = query;
-
- // First check if monitor exists and user has access
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!monitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, monitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Determine the time bucket function based on the bucket parameter
- let timeBucketFn: string;
- let dateFormat: string;
- switch (bucket) {
- case "hour":
- timeBucketFn = `toStartOfHour(toTimeZone(timestamp, '${timeZone}'))`;
- dateFormat = "%Y-%m-%d %H:00:00";
- break;
- case "week":
- timeBucketFn = `toStartOfWeek(toTimeZone(timestamp, '${timeZone}'))`;
- dateFormat = "%Y-%m-%d";
- break;
- case "day":
- default:
- timeBucketFn = `toStartOfDay(toTimeZone(timestamp, '${timeZone}'))`;
- dateFormat = "%Y-%m-%d";
- break;
- }
-
- // Query to get bucketed uptime data
- const query_str = `
- SELECT
- toTimeZone(bucket_time_tz, 'UTC') as bucket_time,
- formatDateTime(bucket_time_tz, '${dateFormat}', '${timeZone}') as bucket_formatted,
- count() as total_checks,
- countIf(status = 'success') as successful_checks,
- countIf(status = 'failure') as failed_checks,
- countIf(status = 'timeout') as timeout_checks,
- if(count() > 0,
- round(100.0 * countIf(status = 'success') / count(), 2),
- 100.0) as uptime_percentage
- FROM (
- SELECT
- *,
- ${timeBucketFn} as bucket_time_tz
- FROM monitor_events
- WHERE monitor_id = {monitorId: UInt32}
- AND timestamp >= now() - INTERVAL {days: UInt32} DAY
- )
- GROUP BY bucket_time_tz
- ORDER BY bucket_time_tz DESC
- `;
-
- const result = await clickhouse.query({
- query: query_str,
- query_params: {
- monitorId: Number(monitorId),
- days: days,
- },
- format: "JSONEachRow",
- });
-
- const buckets = await processResults(result);
-
- // Generate all expected buckets for the time range
- // Use timezone-aware date generation
- const nowInTz = new Date(new Date().toLocaleString("en-US", { timeZone }));
- const allBuckets: Array<{
- bucket_time: string;
- bucket_formatted: string;
- total_checks: number;
- successful_checks: number;
- failed_checks: number;
- timeout_checks: number;
- uptime_percentage: number;
- }> = [];
-
- for (let i = 0; i < days; i++) {
- const date = new Date(nowInTz);
-
- if (bucket === "hour") {
- // For hourly buckets, generate 24 buckets per day
- for (let h = 0; h < 24; h++) {
- date.setDate(date.getDate() - i);
- date.setHours(23 - h, 0, 0, 0);
- if (date <= nowInTz) {
- allBuckets.push({
- bucket_time: date.toISOString(),
- bucket_formatted: date.toISOString().slice(0, 13) + ":00:00",
- total_checks: 0,
- successful_checks: 0,
- failed_checks: 0,
- timeout_checks: 0,
- uptime_percentage: 100.0,
- });
- }
- }
- } else if (bucket === "week") {
- // For weekly buckets, calculate start of week
- date.setDate(date.getDate() - i * 7);
- const dayOfWeek = date.getDay();
- const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // Monday as start
- date.setDate(diff);
- date.setHours(0, 0, 0, 0);
-
- if (allBuckets.length === 0 || !allBuckets.some(b => b.bucket_formatted === date.toISOString().slice(0, 10))) {
- allBuckets.push({
- bucket_time: date.toISOString(),
- bucket_formatted: date.toISOString().slice(0, 10),
- total_checks: 0,
- successful_checks: 0,
- failed_checks: 0,
- timeout_checks: 0,
- uptime_percentage: 100.0,
- });
- }
- } else {
- // Daily buckets
- date.setDate(date.getDate() - i);
- date.setHours(0, 0, 0, 0);
- allBuckets.push({
- bucket_time: date.toISOString(),
- bucket_formatted: date.toISOString().slice(0, 10),
- total_checks: 0,
- successful_checks: 0,
- failed_checks: 0,
- timeout_checks: 0,
- uptime_percentage: 100.0,
- });
- }
- }
-
- // Merge actual data with empty buckets
- const bucketsMap = new Map(buckets.map((b: any) => [b.bucket_formatted, b]));
-
- const mergedBuckets = allBuckets.map(emptyBucket => {
- const actualData = bucketsMap.get(emptyBucket.bucket_formatted);
- return actualData || emptyBucket;
- });
-
- // Sort by bucket_time ascending (oldest first) for frontend display
- mergedBuckets.sort((a, b) => new Date(a.bucket_time).getTime() - new Date(b.bucket_time).getTime());
-
- return reply.status(200).send({
- buckets: mergedBuckets,
- bucket,
- days,
- monitorId: Number(monitorId),
- });
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error retrieving monitor uptime buckets");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getMonitors.ts b/server/src/api/uptime/getMonitors.ts
deleted file mode 100644
index 9a7e3baee..000000000
--- a/server/src/api/uptime/getMonitors.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { and, eq, inArray, desc } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { DateTime } from "luxon";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { processResults } from "../analytics/utils/utils.js";
-import { getMonitorsQuerySchema, type GetMonitorsQuery } from "./schemas.js";
-
-interface GetMonitorsRequest {
- Querystring: GetMonitorsQuery;
-}
-
-export async function getMonitors(request: FastifyRequest<GetMonitorsRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- // Get user's organizations
- const userOrgs = await db
- .select({ organizationId: member.organizationId })
- .from(member)
- .where(eq(member.userId, userId));
-
- if (userOrgs.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- try {
- // Validate query parameters with Zod
- const query = getMonitorsQuerySchema.parse(request.query);
- const { enabled, monitorType, organizationId, limit, offset } = query;
-
- // Build where conditions
- const orgIds = userOrgs.map(org => org.organizationId);
- const conditions = [];
-
- // Filter by specific organization if provided, otherwise all user's organizations
- if (organizationId) {
- // Check if user has access to the specified organization
- if (!orgIds.includes(organizationId)) {
- return reply.status(403).send({ error: "Access denied to organization" });
- }
- conditions.push(eq(uptimeMonitors.organizationId, organizationId));
- } else {
- // Use inArray for multiple orgs
- conditions.push(inArray(uptimeMonitors.organizationId, orgIds));
- }
-
- if (enabled !== undefined) {
- conditions.push(eq(uptimeMonitors.enabled, enabled));
- }
-
- if (monitorType) {
- conditions.push(eq(uptimeMonitors.monitorType, monitorType));
- }
-
- // Get monitors with their status
- const monitors = await db
- .select({
- monitor: uptimeMonitors,
- status: uptimeMonitorStatus,
- })
- .from(uptimeMonitors)
- .leftJoin(uptimeMonitorStatus, eq(uptimeMonitors.id, uptimeMonitorStatus.monitorId))
- .where(and(...conditions))
- .orderBy(desc(uptimeMonitors.createdAt))
- .limit(limit)
- .offset(offset);
-
- // Get monitor IDs for uptime calculations
- const monitorIds = monitors.map(m => m.monitor.id);
-
- // Calculate uptime percentages from ClickHouse if we have monitors
- let uptimeData: Record<number, { percentage24h: number; percentage7d: number; percentage30d: number }> = {};
-
- if (monitorIds.length > 0) {
- try {
- const now = DateTime.now();
- const periods = [
- { key: "24h", startTime: now.minus({ hours: 24 }).toFormat("yyyy-MM-dd HH:mm:ss") },
- { key: "7d", startTime: now.minus({ days: 7 }).toFormat("yyyy-MM-dd HH:mm:ss") },
- { key: "30d", startTime: now.minus({ days: 30 }).toFormat("yyyy-MM-dd HH:mm:ss") },
- ];
-
- // Run queries for each period
- const uptimeResults = await Promise.all(
- periods.map(async ({ key, startTime }) => {
- const query = `
- SELECT
- monitor_id,
- countIf(status = 'success') as successful_checks,
- count() as total_checks
- FROM monitor_events
- WHERE monitor_id IN {monitorIds:Array(UInt32)}
- AND timestamp >= {startTime:String}
- GROUP BY monitor_id
- `;
-
- const result = await clickhouse.query({
- query,
- query_params: {
- monitorIds,
- startTime,
- },
- format: "JSONEachRow",
- });
-
- const data = await processResults<{
- monitor_id: number;
- successful_checks: number;
- total_checks: number;
- }>(result);
-
- return { key, data };
- })
- );
-
- // Organize results by monitor ID
- monitorIds.forEach(monitorId => {
- uptimeData[monitorId] = {
- percentage24h: 0,
- percentage7d: 0,
- percentage30d: 0,
- };
- });
-
- uptimeResults.forEach(({ key, data }) => {
- data.forEach(row => {
- const percentage = row.total_checks > 0 ? (row.successful_checks / row.total_checks) * 100 : 0;
-
- if (key === "24h") uptimeData[row.monitor_id].percentage24h = percentage;
- else if (key === "7d") uptimeData[row.monitor_id].percentage7d = percentage;
- else if (key === "30d") uptimeData[row.monitor_id].percentage30d = percentage;
- });
- });
- } catch (error) {
- request.log.error({ err: error }, "Error calculating uptime percentages");
- // Continue without uptime data rather than failing the entire request
- }
- }
-
- const result = monitors.map(row => ({
- ...row.monitor,
- status: row.status
- ? {
- ...row.status,
- uptimePercentage24h: uptimeData[row.monitor.id]?.percentage24h || null,
- uptimePercentage7d: uptimeData[row.monitor.id]?.percentage7d || null,
- uptimePercentage30d: uptimeData[row.monitor.id]?.percentage30d || null,
- }
- : null,
- }));
-
- return reply.status(200).send(result);
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error retrieving monitors");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/getRegions.ts b/server/src/api/uptime/getRegions.ts
deleted file mode 100644
index dafe6dcb6..000000000
--- a/server/src/api/uptime/getRegions.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { agentRegions } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-
-export async function getRegions(request: FastifyRequest, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // Get all enabled regions
- const regions = await db
- .select({
- code: agentRegions.code,
- name: agentRegions.name,
- enabled: agentRegions.enabled,
- isHealthy: agentRegions.isHealthy,
- lastHealthCheck: agentRegions.lastHealthCheck,
- })
- .from(agentRegions)
- .where(eq(agentRegions.enabled, true))
- .orderBy(agentRegions.code);
-
- // Format response
- const formattedRegions = regions.map(region => ({
- code: region.code,
- name: region.name,
- isHealthy: region.isHealthy ?? true,
- lastHealthCheck: region.lastHealthCheck,
- isLocal: region.code === "local",
- }));
-
- return reply.send({
- regions: formattedRegions,
- });
- } catch (error) {
- request.log.error({ err: error }, "Error fetching regions");
- return reply.status(500).send({ error: "Failed to fetch regions" });
- }
-}
diff --git a/server/src/api/uptime/incidents.ts b/server/src/api/uptime/incidents.ts
deleted file mode 100644
index 9d0a01400..000000000
--- a/server/src/api/uptime/incidents.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-import { and, desc, eq, inArray, sql } from "drizzle-orm";
-import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
-import { z } from "zod";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeIncidents, uptimeMonitors } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { getUserOrganizations } from "./utils.js";
-
-// Schemas
-const incidentStatusSchema = z.enum(["active", "acknowledged", "resolved", "all"]);
-
-const getIncidentsQuerySchema = z.object({
- status: incidentStatusSchema.default("all"),
- limit: z.coerce.number().int().min(1).max(100).default(50),
- offset: z.coerce.number().int().min(0).default(0),
-});
-
-const incidentIdParamsSchema = z.object({
- id: z.coerce.number().int(),
-});
-
-const incidentSchema = z.object({
- id: z.number(),
- organizationId: z.string(),
- monitorId: z.number(),
- monitorName: z.string(),
- region: z.string().nullable(),
- startTime: z.string(),
- endTime: z.string().nullable(),
- status: z.string(),
- acknowledgedBy: z.string().nullable(),
- acknowledgedAt: z.string().nullable(),
- resolvedBy: z.string().nullable(),
- resolvedAt: z.string().nullable(),
- lastError: z.string().nullable(),
- lastErrorType: z.string().nullable(),
- failureCount: z.number(),
- createdAt: z.string(),
- updatedAt: z.string(),
-});
-
-export const incidentsRoutes = async (server: FastifyInstance) => {
- // Get incidents
- server.route({
- method: "GET",
- url: "/api/uptime/incidents",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- // Get user's organizations
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- const query = getIncidentsQuerySchema.parse(request.query);
- const { status, limit, offset } = query;
-
- // Build where conditions
- const conditions = [inArray(uptimeIncidents.organizationId, organizationIds)];
-
- if (status !== "all") {
- conditions.push(eq(uptimeIncidents.status, status));
- }
-
- // Use SQL to group incidents by monitor and aggregate regions
- const groupedIncidents = await db
- .select({
- id: sql<number>`MIN(${uptimeIncidents.id})`,
- organizationId: sql<string>`MIN(${uptimeIncidents.organizationId})`,
- monitorId: uptimeIncidents.monitorId,
- monitorName: sql<string>`
- CASE
- WHEN ${uptimeMonitors.name} IS NOT NULL AND ${uptimeMonitors.name} != '' THEN ${uptimeMonitors.name}
- WHEN ${uptimeMonitors.monitorType} = 'http' THEN COALESCE(${uptimeMonitors.httpConfig}->>'url', 'HTTP Monitor')
- WHEN ${uptimeMonitors.monitorType} = 'tcp' THEN CONCAT(${uptimeMonitors.tcpConfig}->>'host', ':', ${uptimeMonitors.tcpConfig}->>'port')
- ELSE 'Unknown Monitor'
- END
- `,
- affectedRegions: sql<
- string[]
- >`ARRAY_REMOVE(ARRAY_AGG(DISTINCT ${uptimeIncidents.region} ORDER BY ${uptimeIncidents.region}), NULL)`,
- startTime: sql<string>`MIN(${uptimeIncidents.startTime})`,
- endTime: sql<string>`MAX(${uptimeIncidents.endTime})`,
- status: uptimeIncidents.status,
- acknowledgedBy: sql<string>`MAX(${uptimeIncidents.acknowledgedBy})`,
- acknowledgedAt: sql<string>`MAX(${uptimeIncidents.acknowledgedAt})`,
- resolvedBy: sql<string>`MAX(${uptimeIncidents.resolvedBy})`,
- resolvedAt: sql<string>`MAX(${uptimeIncidents.resolvedAt})`,
- lastError: sql<string>`(ARRAY_AGG(${uptimeIncidents.lastError} ORDER BY ${uptimeIncidents.updatedAt} DESC))[1]`,
- lastErrorType: sql<string>`(ARRAY_AGG(${uptimeIncidents.lastErrorType} ORDER BY ${uptimeIncidents.updatedAt} DESC))[1]`,
- failureCount: sql<number>`SUM(${uptimeIncidents.failureCount})`,
- createdAt: sql<string>`MIN(${uptimeIncidents.createdAt})`,
- updatedAt: sql<string>`MAX(${uptimeIncidents.updatedAt})`,
- })
- .from(uptimeIncidents)
- .leftJoin(uptimeMonitors, eq(uptimeIncidents.monitorId, uptimeMonitors.id))
- .where(and(...conditions))
- .groupBy(
- uptimeIncidents.monitorId,
- uptimeIncidents.status,
- sql`CASE
- WHEN ${uptimeIncidents.status} = 'resolved' THEN
- DATE_TRUNC('hour', ${uptimeIncidents.endTime})
- ELSE
- NULL
- END`,
- uptimeMonitors.name,
- uptimeMonitors.monitorType,
- uptimeMonitors.httpConfig,
- uptimeMonitors.tcpConfig
- )
- .orderBy(desc(sql`MIN(${uptimeIncidents.startTime})`))
- .limit(limit)
- .offset(offset);
-
- // Get total count for pagination
- const totalCountResult = await db
- .select({
- count: sql<number>`COUNT(DISTINCT
- CONCAT(
- ${uptimeIncidents.monitorId},
- '-',
- ${uptimeIncidents.status},
- '-',
- CASE
- WHEN ${uptimeIncidents.status} = 'resolved' THEN
- DATE_TRUNC('hour', ${uptimeIncidents.endTime})::text
- ELSE
- ''
- END
- )
- )`,
- })
- .from(uptimeIncidents)
- .where(and(...conditions));
-
- const total = Number(totalCountResult[0]?.count || 0);
-
- return reply.send({
- incidents: groupedIncidents,
- pagination: {
- total,
- limit,
- offset,
- },
- });
- },
- });
-
- // Acknowledge incident
- server.route({
- method: "PATCH",
- url: "/api/uptime/incidents/:id/acknowledge",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const params = incidentIdParamsSchema.parse(request.params);
- const { id } = params;
-
- // Get user's organizations
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- // Verify incident belongs to user's organization
- const incident = await db
- .select()
- .from(uptimeIncidents)
- .where(and(eq(uptimeIncidents.id, id), inArray(uptimeIncidents.organizationId, organizationIds)))
- .limit(1);
-
- if (!incident[0]) {
- return reply.code(404).send({ error: "Incident not found" });
- }
-
- if (incident[0].status === "resolved") {
- return reply.code(400).send({ error: "Cannot acknowledge resolved incident" });
- }
-
- // Update incident
- const now = new Date().toISOString();
- const [updated] = await db
- .update(uptimeIncidents)
- .set({
- status: "acknowledged",
- acknowledgedBy: userId,
- acknowledgedAt: now,
- updatedAt: now,
- })
- .where(eq(uptimeIncidents.id, id))
- .returning({
- id: uptimeIncidents.id,
- status: uptimeIncidents.status,
- acknowledgedBy: uptimeIncidents.acknowledgedBy,
- acknowledgedAt: uptimeIncidents.acknowledgedAt,
- });
-
- return reply.send({
- success: true,
- incident: updated,
- });
- },
- });
-
- // Resolve incident
- server.route({
- method: "PATCH",
- url: "/api/uptime/incidents/:id/resolve",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const params = incidentIdParamsSchema.parse(request.params);
- const { id } = params;
-
- // Get user's organizations
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- // Verify incident belongs to user's organization
- const incident = await db
- .select()
- .from(uptimeIncidents)
- .where(and(eq(uptimeIncidents.id, id), inArray(uptimeIncidents.organizationId, organizationIds)))
- .limit(1);
-
- if (!incident[0]) {
- return reply.code(404).send({ error: "Incident not found" });
- }
-
- if (incident[0].status === "resolved") {
- return reply.code(400).send({ error: "Incident already resolved" });
- }
-
- // Update incident
- const now = new Date().toISOString();
- const [updated] = await db
- .update(uptimeIncidents)
- .set({
- status: "resolved",
- resolvedBy: userId,
- resolvedAt: now,
- endTime: now,
- updatedAt: now,
- })
- .where(eq(uptimeIncidents.id, id))
- .returning({
- id: uptimeIncidents.id,
- status: uptimeIncidents.status,
- resolvedBy: uptimeIncidents.resolvedBy,
- resolvedAt: uptimeIncidents.resolvedAt,
- endTime: uptimeIncidents.endTime,
- });
-
- return reply.send({
- success: true,
- incident: updated,
- });
- },
- });
-};
diff --git a/server/src/api/uptime/notifications.ts b/server/src/api/uptime/notifications.ts
deleted file mode 100644
index c5c904b77..000000000
--- a/server/src/api/uptime/notifications.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-import { and, eq, inArray } from "drizzle-orm";
-import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
-import { DateTime } from "luxon";
-import { z } from "zod";
-import { db } from "../../db/postgres/postgres.js";
-import { notificationChannels } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { NotificationService } from "../../services/uptime/notificationService.js";
-import { getUserOrganizations } from "./utils.js";
-
-// Schemas
-const channelTypeSchema = z.enum(["email", "discord", "slack", "sms"]);
-
-const channelConfigSchema = z.object({
- email: z.string().email().optional(),
- webhookUrl: z.string().url().optional(),
- slackWebhookUrl: z.string().url().optional(),
- slackChannel: z.string().optional(),
- phoneNumber: z.string().optional(),
- provider: z.string().optional(),
-});
-
-const createChannelSchema = z.object({
- type: channelTypeSchema,
- name: z.string().min(1).max(100),
- config: channelConfigSchema,
- monitorIds: z.array(z.number()).nullable().optional(),
- triggerEvents: z.array(z.string()).default(["down", "recovery"]).optional(),
- cooldownMinutes: z.number().int().min(0).max(1440).default(5).optional(),
-});
-
-const updateChannelSchema = z.object({
- name: z.string().min(1).max(100).optional(),
- enabled: z.boolean().optional(),
- config: channelConfigSchema.optional(),
- monitorIds: z.array(z.number()).nullable().optional(),
- triggerEvents: z.array(z.string()).optional(),
- cooldownMinutes: z.number().int().min(0).max(1440).optional(),
-});
-
-const channelIdParamsSchema = z.object({
- id: z.coerce.number().int(),
-});
-
-export const notificationRoutes = async (server: FastifyInstance) => {
- // Get all notification channels
- server.route({
- method: "GET",
- url: "/api/uptime/notification-channels",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- const channels = await db
- .select()
- .from(notificationChannels)
- .where(inArray(notificationChannels.organizationId, organizationIds));
-
- return reply.send({ channels });
- },
- });
-
- // Create notification channel
- server.route({
- method: "POST",
- url: "/api/uptime/notification-channels",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- // For creation, use the first organization (assuming user can only create in their primary org)
- const organizationId = organizationIds[0];
-
- const body = createChannelSchema.parse(request.body);
- const { type, name, config, monitorIds, triggerEvents, cooldownMinutes } = body;
-
- // Validate config based on type
- if (type === "email" && !config.email) {
- return reply.code(400).send({ error: "Email address is required for email channel" });
- }
- if (type === "discord" && !config.webhookUrl) {
- return reply.code(400).send({ error: "Webhook URL is required for Discord channel" });
- }
- if (type === "slack" && !config.slackWebhookUrl) {
- return reply.code(400).send({ error: "Webhook URL is required for Slack channel" });
- }
- if (type === "sms" && !config.phoneNumber) {
- return reply.code(400).send({ error: "Phone number is required for SMS channel" });
- }
-
- const [channel] = await db
- .insert(notificationChannels)
- .values({
- organizationId,
- type,
- name,
- config,
- monitorIds: monitorIds || null,
- triggerEvents: triggerEvents || ["down", "recovery"],
- cooldownMinutes: cooldownMinutes || 5,
- createdBy: userId,
- })
- .returning();
-
- return reply.send(channel);
- },
- });
-
- // Update notification channel
- server.route({
- method: "PUT",
- url: "/api/uptime/notification-channels/:id",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- const params = channelIdParamsSchema.parse(request.params);
- const { id } = params;
- const updates = updateChannelSchema.parse(request.body);
-
- // Verify channel belongs to user's organization
- const [channel] = await db
- .select()
- .from(notificationChannels)
- .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
- .limit(1);
-
- if (!channel) {
- return reply.code(404).send({ error: "Channel not found" });
- }
-
- const [updated] = await db
- .update(notificationChannels)
- .set({
- ...updates,
- updatedAt: new Date().toISOString(),
- })
- .where(eq(notificationChannels.id, id))
- .returning();
-
- return reply.send(updated);
- },
- });
-
- // Delete notification channel
- server.route({
- method: "DELETE",
- url: "/api/uptime/notification-channels/:id",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- const params = channelIdParamsSchema.parse(request.params);
- const { id } = params;
-
- // Verify channel belongs to user's organization
- const [channel] = await db
- .select()
- .from(notificationChannels)
- .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
- .limit(1);
-
- if (!channel) {
- return reply.code(404).send({ error: "Channel not found" });
- }
-
- // Delete the channel
- await db.delete(notificationChannels).where(eq(notificationChannels.id, id));
-
- return reply.send({ success: true });
- },
- });
-
- // Test notification channel
- server.route({
- method: "POST",
- url: "/api/uptime/notification-channels/:id/test",
- handler: async (request: FastifyRequest, reply: FastifyReply) => {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- const organizationIds = await getUserOrganizations(userId);
-
- if (organizationIds.length === 0) {
- return reply.status(403).send({ error: "No organization access" });
- }
-
- const params = channelIdParamsSchema.parse(request.params);
- const { id } = params;
-
- // Verify channel belongs to user's organization
- const [channel] = await db
- .select()
- .from(notificationChannels)
- .where(and(eq(notificationChannels.id, id), inArray(notificationChannels.organizationId, organizationIds)))
- .limit(1);
-
- if (!channel) {
- return reply.code(404).send({ error: "Channel not found" });
- }
-
- // Create a test monitor and incident for the notification
- const testMonitor = {
- id: 0,
- organizationId: channel.organizationId,
- name: "Test Monitor",
- monitorType: "http",
- httpConfig: {
- url: "https://example.com",
- },
- tcpConfig: null,
- };
-
- const testIncident = {
- id: 0,
- region: "test",
- startTime: DateTime.now().toSQL()!,
- endTime: null,
- lastError: "This is a test notification",
- lastErrorType: "test",
- status: "active",
- };
-
- // Send test notification
- const notificationService = new NotificationService();
-
- try {
- // Send the test notification to only this specific channel
- await notificationService.sendTestNotification(channel, testMonitor, testIncident, "down");
-
- return reply.send({
- success: true,
- message: `Test notification sent to ${channel.type} channel: ${channel.name}`,
- });
- } catch (error) {
- request.log.error({ err: error }, "Failed to send test notification");
- return reply.code(500).send({
- success: false,
- message: "Failed to send test notification",
- error: error instanceof Error ? error.message : "Unknown error",
- });
- }
- },
- });
-};
diff --git a/server/src/api/uptime/schemas.ts b/server/src/api/uptime/schemas.ts
deleted file mode 100644
index 27aed9e91..000000000
--- a/server/src/api/uptime/schemas.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { z } from "zod";
-
-// HTTP method enum
-const httpMethodSchema = z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]);
-
-// Auth type enum
-const authTypeSchema = z.enum(["none", "basic", "bearer", "api_key", "custom_header"]);
-
-// IP version enum
-const ipVersionSchema = z.enum(["any", "ipv4", "ipv6"]);
-
-// Auth credentials schema
-const authCredentialsSchema = z.object({
- username: z.string().optional(),
- password: z.string().optional(),
- token: z.string().optional(),
- headerName: z.string().optional(),
- headerValue: z.string().optional(),
-});
-
-// Auth schema
-const authSchema = z.object({
- type: authTypeSchema,
- credentials: authCredentialsSchema.optional(),
-});
-
-// HTTP config schema
-const httpConfigSchema = z.object({
- url: z.string().url("Invalid URL format"),
- method: httpMethodSchema.default("GET"),
- headers: z.record(z.string()).optional(),
- body: z.string().optional(),
- auth: authSchema.optional(),
- followRedirects: z.boolean().default(true),
- timeoutMs: z.number().int().positive().max(300000).optional(), // Max 5 minutes
- ipVersion: ipVersionSchema.optional(),
- userAgent: z.string().max(256).optional(),
-});
-
-// TCP config schema
-const tcpConfigSchema = z.object({
- host: z.string().min(1, "Host is required"),
- port: z.number().int().min(1).max(65535, "Port must be between 1 and 65535"),
- timeoutMs: z.number().int().positive().max(300000).optional(), // Max 5 minutes
-});
-
-// Validation rule schemas
-const statusCodeRuleSchema = z.object({
- type: z.literal("status_code"),
- operator: z.enum(["equals", "not_equals", "in", "not_in"]),
- value: z.union([z.number(), z.array(z.number())]),
-});
-
-const responseTimeRuleSchema = z.object({
- type: z.literal("response_time"),
- operator: z.enum(["less_than", "greater_than"]),
- value: z.number().positive(),
-});
-
-const bodyContainsRuleSchema = z.object({
- type: z.enum(["response_body_contains", "response_body_not_contains"]),
- value: z.string(),
- caseSensitive: z.boolean().optional(),
-});
-
-const headerExistsRuleSchema = z.object({
- type: z.literal("header_exists"),
- header: z.string(),
-});
-
-const headerValueRuleSchema = z.object({
- type: z.literal("header_value"),
- header: z.string(),
- operator: z.enum(["equals", "contains"]),
- value: z.string(),
-});
-
-const responseSizeRuleSchema = z.object({
- type: z.literal("response_size"),
- operator: z.enum(["less_than", "greater_than"]),
- value: z.number().positive(),
-});
-
-const validationRuleSchema = z.discriminatedUnion("type", [
- statusCodeRuleSchema,
- responseTimeRuleSchema,
- bodyContainsRuleSchema,
- headerExistsRuleSchema,
- headerValueRuleSchema,
- responseSizeRuleSchema,
-]);
-
-// Create monitor schema
-export const createMonitorSchema = z
- .object({
- organizationId: z.string().min(1, "Organization ID is required"),
- name: z.string().max(256).optional(), // Made optional
- monitorType: z.enum(["http", "tcp"]),
- intervalSeconds: z.number().int().min(30).max(86400, "Interval must be between 60 and 86400 seconds"),
- enabled: z.boolean().default(true),
- httpConfig: httpConfigSchema.optional(),
- tcpConfig: tcpConfigSchema.optional(),
- validationRules: z.array(validationRuleSchema).default([]),
- monitoringType: z.enum(["local", "global"]).default("local"),
- selectedRegions: z.array(z.string()).default([]),
- })
- .refine(
- data => {
- if (data.monitorType === "http") {
- return data.httpConfig !== undefined;
- }
- if (data.monitorType === "tcp") {
- return data.tcpConfig !== undefined;
- }
- return false;
- },
- {
- message: "Monitor type specific configuration is required",
- }
- );
-
-// Update monitor schema (similar to create but with optional fields)
-export const updateMonitorSchema = z.object({
- name: z.string().max(256).optional(), // Allow empty string to remove name
- intervalSeconds: z.number().int().min(30).max(86400).optional(),
- enabled: z.boolean().optional(),
- httpConfig: httpConfigSchema.optional(),
- tcpConfig: tcpConfigSchema.optional(),
- validationRules: z.array(validationRuleSchema).optional(),
- monitoringType: z.enum(["local", "global"]).optional(),
- selectedRegions: z.array(z.string()).optional(),
-});
-
-// Query params schemas
-export const getMonitorsQuerySchema = z.object({
- organizationId: z.string().optional(),
- enabled: z
- .enum(["true", "false"])
- .transform(val => val === "true")
- .optional(),
- monitorType: z.enum(["http", "tcp"]).optional(),
- limit: z.string().transform(Number).pipe(z.number().int().positive().max(100)).default("50"),
- offset: z.string().transform(Number).pipe(z.number().int().nonnegative()).default("0"),
-});
-
-export const getMonitorEventsQuerySchema = z.object({
- status: z.enum(["success", "failure", "timeout"]).optional(),
- region: z.string().optional(),
- limit: z.string().transform(Number).pipe(z.number().int().positive().max(100)).default("20"),
- offset: z.string().transform(Number).pipe(z.number().int().nonnegative()).default("0"),
-});
-
-export const getMonitorStatsQuerySchema = z.object({
- hours: z.string().transform(Number).pipe(z.number().int().positive().max(8760)).optional(), // Max 1 year in hours
- region: z.string().optional(),
- bucket: z
- .enum(["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour", "day", "week", "month", "year"])
- .optional(),
-});
-
-// Type exports
-export type CreateMonitorInput = z.infer<typeof createMonitorSchema>;
-export type UpdateMonitorInput = z.infer<typeof updateMonitorSchema>;
-export type GetMonitorsQuery = z.infer<typeof getMonitorsQuerySchema>;
-export type GetMonitorEventsQuery = z.infer<typeof getMonitorEventsQuerySchema>;
-export type GetMonitorStatsQuery = z.infer<typeof getMonitorStatsQuerySchema>;
diff --git a/server/src/api/uptime/updateMonitor.ts b/server/src/api/uptime/updateMonitor.ts
deleted file mode 100644
index cfe5a3e44..000000000
--- a/server/src/api/uptime/updateMonitor.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { and, eq } from "drizzle-orm";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, member } from "../../db/postgres/schema.js";
-import { getSessionFromReq } from "../../lib/auth-utils.js";
-import { uptimeService } from "../../services/uptime/uptimeService.js";
-import { updateMonitorSchema, type UpdateMonitorInput } from "./schemas.js";
-
-interface UpdateMonitorRequest {
- Params: {
- monitorId: string;
- };
- Body: UpdateMonitorInput;
-}
-
-export async function updateMonitor(request: FastifyRequest<UpdateMonitorRequest>, reply: FastifyReply) {
- const session = await getSessionFromReq(request);
- const userId = session?.user?.id;
- const { monitorId } = request.params;
-
- if (!userId) {
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- try {
- // First get the monitor to check if it exists and user has access
- const existingMonitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, Number(monitorId)),
- });
-
- if (!existingMonitor) {
- return reply.status(404).send({ error: "Monitor not found" });
- }
-
- // Check if user has access to the monitor's organization
- const userHasAccess = await db.query.member.findFirst({
- where: and(eq(member.userId, userId), eq(member.organizationId, existingMonitor.organizationId)),
- });
-
- if (!userHasAccess) {
- return reply.status(403).send({ error: "Access denied" });
- }
-
- // Validate request body with Zod
- const updateData = updateMonitorSchema.parse(request.body);
-
- // Additional validation for monitor type specific config if changing config
- if (existingMonitor.monitorType === "http" && updateData.httpConfig) {
- if (!updateData.httpConfig.url) {
- return reply.status(400).send({ error: "HTTP monitor requires URL" });
- }
- }
- if (existingMonitor.monitorType === "tcp" && updateData.tcpConfig) {
- if (!updateData.tcpConfig.host || !updateData.tcpConfig.port) {
- return reply.status(400).send({ error: "TCP monitor requires host and port" });
- }
- }
-
- // Update the monitor
- const [updatedMonitor] = await db
- .update(uptimeMonitors)
- .set({
- ...updateData,
- updatedAt: new Date().toISOString(),
- })
- .where(eq(uptimeMonitors.id, Number(monitorId)))
- .returning();
-
- // Update the monitor schedule if interval or enabled status changed
- const intervalChanged =
- updateData.intervalSeconds !== undefined && updateData.intervalSeconds !== existingMonitor.intervalSeconds;
- const enabledChanged = updateData.enabled !== undefined && updateData.enabled !== existingMonitor.enabled;
-
- if (intervalChanged || enabledChanged) {
- const enabled = updateData.enabled !== undefined ? updateData.enabled : existingMonitor.enabled!;
- const intervalSeconds = updateData.intervalSeconds || existingMonitor.intervalSeconds;
-
- await uptimeService.onMonitorUpdated(Number(monitorId), intervalSeconds, enabled);
- }
-
- return reply.status(200).send(updatedMonitor);
- } catch (error) {
- if (error instanceof Error && error.name === "ZodError") {
- const zodError = error as any;
- return reply.status(400).send({
- error: "Validation error",
- details: zodError.errors,
- });
- }
- request.log.error({ err: error }, "Error updating monitor");
- return reply.status(500).send({ error: "Internal server error" });
- }
-}
diff --git a/server/src/api/uptime/utils.ts b/server/src/api/uptime/utils.ts
deleted file mode 100644
index ef415d322..000000000
--- a/server/src/api/uptime/utils.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { eq } from "drizzle-orm";
-import { db } from "../../db/postgres/postgres.js";
-import { member } from "../../db/postgres/schema.js";
-
-export async function getUserOrganizations(userId: string) {
- const userOrgs = await db
- .select({ organizationId: member.organizationId })
- .from(member)
- .where(eq(member.userId, userId));
-
- return userOrgs.map(org => org.organizationId);
-}
diff --git a/server/src/db/clickhouse/schema/core.ts b/server/src/db/clickhouse/schema/core.ts
index cd0421a34..89a79f9d2 100644
--- a/server/src/db/clickhouse/schema/core.ts
+++ b/server/src/db/clickhouse/schema/core.ts
@@ -261,51 +261,4 @@ export async function initializeCoreTables() {
ADD COLUMN IF NOT EXISTS identified_user_id String DEFAULT ''
`
);
-
- await execClickhouseInitStep(
- "create monitor events table",
- `
- CREATE TABLE IF NOT EXISTS monitor_events (
- monitor_id UInt32,
- organization_id String,
- timestamp DateTime,
-
- -- Monitor metadata
- monitor_type LowCardinality(String), -- 'http', 'tcp'
- monitor_url String,
- monitor_name String,
- region LowCardinality(String) DEFAULT 'local',
-
- -- Response data
- status LowCardinality(String), -- 'success', 'failure', 'timeout'
- status_code Nullable(UInt16), -- HTTP status code
- response_time_ms UInt32,
-
- -- HTTP timing breakdown (all in milliseconds)
- dns_time_ms Nullable(UInt32),
- tcp_time_ms Nullable(UInt32),
- tls_time_ms Nullable(UInt32),
- ttfb_ms Nullable(UInt32), -- Time to first byte
- transfer_time_ms Nullable(UInt32),
-
- -- Validation results
- validation_errors Array(String), -- Array of failed validation rules
-
- -- Response metadata (for HTTP)
- response_headers Map(String, String),
- response_size_bytes Nullable(UInt32),
-
- -- TCP specific
- port Nullable(UInt16),
-
- -- Error information
- error_message Nullable(String),
- error_type Nullable(String) -- 'dns_failure', 'connection_timeout', 'ssl_error', etc.
- )
- ENGINE = MergeTree()
- PARTITION BY toYYYYMM(timestamp)
- ORDER BY (organization_id, monitor_id, timestamp)
- SETTINGS ttl_only_drop_parts = 1
- `
- );
}
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 999190e5d..67088983e 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -521,265 +521,6 @@ export const telemetry = pgTable("telemetry", {
clickhouseSizeGb: real("clickhouse_size_gb").notNull(),
});
-// Uptime monitor definitions
-export const uptimeMonitors = pgTable("uptime_monitors", {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- name: text("name"),
- monitorType: text("monitor_type").notNull(), // 'http', 'tcp'
-
- // Common settings
- intervalSeconds: integer("interval_seconds").notNull(),
- enabled: boolean("enabled").default(true),
-
- // HTTP/HTTPS specific configuration
- httpConfig: jsonb("http_config").$type<{
- url: string;
- method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";
- headers?: Record<string, string>;
- body?: string;
- auth?: {
- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
- credentials?: {
- username?: string;
- password?: string;
- token?: string;
- headerName?: string;
- headerValue?: string;
- };
- };
- followRedirects?: boolean;
- timeoutMs?: number;
- ipVersion?: "any" | "ipv4" | "ipv6";
- userAgent?: string;
- }>(),
-
- // TCP specific configuration
- tcpConfig: jsonb("tcp_config").$type<{
- host: string;
- port: number;
- timeoutMs?: number;
- }>(),
-
- // Validation rules
- validationRules: jsonb("validation_rules").notNull().default([]).$type<
- Array<
- | {
- type: "status_code";
- operator: "equals" | "not_equals" | "in" | "not_in";
- value: number | number[];
- }
- | {
- type: "response_time";
- operator: "less_than" | "greater_than";
- value: number;
- }
- | {
- type: "response_body_contains" | "response_body_not_contains";
- value: string;
- caseSensitive?: boolean;
- }
- | {
- type: "header_exists";
- header: string;
- }
- | {
- type: "header_value";
- header: string;
- operator: "equals" | "contains";
- value: string;
- }
- | {
- type: "response_size";
- operator: "less_than" | "greater_than";
- value: number;
- }
- >
- >(),
-
- // Multi-region configuration
- monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'
- selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),
-
- // Metadata
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
-});
-
-// Monitor status tracking
-export const uptimeMonitorStatus = pgTable(
- "uptime_monitor_status",
- {
- monitorId: integer("monitor_id")
- .primaryKey()
- .notNull()
- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
- lastCheckedAt: timestamp("last_checked_at", { mode: "string" }),
- nextCheckAt: timestamp("next_check_at", { mode: "string" }),
- currentStatus: text("current_status").default("unknown"), // 'up', 'down', 'unknown'
- consecutiveFailures: integer("consecutive_failures").default(0),
- consecutiveSuccesses: integer("consecutive_successes").default(0),
- uptimePercentage24h: real("uptime_percentage_24h"),
- uptimePercentage7d: real("uptime_percentage_7d"),
- uptimePercentage30d: real("uptime_percentage_30d"),
- averageResponseTime24h: real("average_response_time_24h"),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- },
- table => [
- foreignKey({
- columns: [table.monitorId],
- foreignColumns: [uptimeMonitors.id],
- name: "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",
- }),
- check("uptime_monitor_status_current_status_check", sql`current_status IN ('up', 'down', 'unknown')`),
- check("uptime_monitor_status_uptime_24h_check", sql`uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100`),
- check("uptime_monitor_status_uptime_7d_check", sql`uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100`),
- check("uptime_monitor_status_uptime_30d_check", sql`uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100`),
- index("uptime_monitor_status_updated_at_idx").on(table.updatedAt),
- ]
-);
-
-// Alert configuration (scaffolding)
-export const uptimeAlerts = pgTable(
- "uptime_alerts",
- {
- id: serial("id").primaryKey().notNull(),
- monitorId: integer("monitor_id")
- .notNull()
- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
- alertType: text("alert_type").notNull(), // 'email', 'webhook', 'slack', etc.
- alertConfig: jsonb("alert_config").notNull(), // Type-specific configuration
- conditions: jsonb("conditions").notNull().$type<{
- consecutiveFailures?: number;
- responseTimeThresholdMs?: number;
- uptimePercentageThreshold?: number;
- }>(),
- enabled: boolean("enabled").default(true),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- },
- table => [
- foreignKey({
- columns: [table.monitorId],
- foreignColumns: [uptimeMonitors.id],
- name: "uptime_alerts_monitor_id_uptime_monitors_id_fk",
- }),
- ]
-);
-
-// Alert history (scaffolding)
-export const uptimeAlertHistory = pgTable(
- "uptime_alert_history",
- {
- id: serial("id").primaryKey().notNull(),
- alertId: integer("alert_id")
- .notNull()
- .references(() => uptimeAlerts.id, { onDelete: "cascade" }),
- monitorId: integer("monitor_id")
- .notNull()
- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
- triggeredAt: timestamp("triggered_at", { mode: "string" }).defaultNow(),
- resolvedAt: timestamp("resolved_at", { mode: "string" }),
- alertData: jsonb("alert_data"), // Context about what triggered the alert
- },
- table => [
- foreignKey({
- columns: [table.alertId],
- foreignColumns: [uptimeAlerts.id],
- name: "uptime_alert_history_alert_id_uptime_alerts_id_fk",
- }),
- foreignKey({
- columns: [table.monitorId],
- foreignColumns: [uptimeMonitors.id],
- name: "uptime_alert_history_monitor_id_uptime_monitors_id_fk",
- }),
- ]
-);
-
-// Agent regions for VPS-based monitoring
-export const agentRegions = pgTable("agent_regions", {
- code: text("code").primaryKey().notNull(), // Region code (e.g., 'us-east', 'europe')
- name: text("name").notNull(), // Region display name
- endpointUrl: text("endpoint_url").notNull(), // Agent endpoint URL
- enabled: boolean("enabled").default(true),
- lastHealthCheck: timestamp("last_health_check", { mode: "string" }),
- isHealthy: boolean("is_healthy").default(true),
-});
-
-// Uptime incidents table
-export const uptimeIncidents = pgTable("uptime_incidents", {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- monitorId: integer("monitor_id")
- .notNull()
- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),
- region: text("region"), // Region where incident occurred
-
- // Incident timing
- startTime: timestamp("start_time", { mode: "string" }).notNull(),
- endTime: timestamp("end_time", { mode: "string" }), // null if ongoing
-
- // Status
- status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'
-
- // Acknowledgement details
- acknowledgedBy: text("acknowledged_by").references(() => user.id, { onDelete: "set null" }),
- acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),
-
- // Resolution details
- resolvedBy: text("resolved_by").references(() => user.id, { onDelete: "set null" }),
- resolvedAt: timestamp("resolved_at", { mode: "string" }),
-
- // Error details
- lastError: text("last_error"),
- lastErrorType: text("last_error_type"),
- failureCount: integer("failure_count").default(1),
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
-});
-
-// Notification channels table
-export const notificationChannels = pgTable("notification_channels", {
- id: serial("id").primaryKey().notNull(),
- organizationId: text("organization_id")
- .notNull()
- .references(() => organization.id),
- type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'
- name: text("name").notNull(),
- enabled: boolean("enabled").default(true),
-
- // Channel-specific configuration
- config: jsonb("config").notNull().$type<{
- // Email config
- email?: string;
-
- // Discord config
- webhookUrl?: string;
-
- // Slack config
- slackWebhookUrl?: string;
- slackChannel?: string;
-
- // SMS config (placeholder)
- phoneNumber?: string;
- provider?: string;
- }>(),
-
- // Monitor selection and notification settings
- monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors
- triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'
- cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications
- lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),
-
- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),
- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),
- createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
-});
-
// Google Search Console connections table
export const gscConnections = pgTable("gsc_connections", {
siteId: integer("site_id")
diff --git a/server/src/db/redis/redis.ts b/server/src/db/redis/redis.ts
index bccc2018b..739be566b 100644
--- a/server/src/db/redis/redis.ts
+++ b/server/src/db/redis/redis.ts
@@ -42,8 +42,7 @@ function createRedisClient(label: string): Redis {
}
// Shared request/response client for bot detection (anomaly scoring + stats) and
-// general use. Distinct from the BullMQ connections used by the uptime service
-// (those have their own settings).
+// general use.
export const redis = createRedisClient("main");
// Dedicated connection for per-event session resolution. Isolated from `redis`
diff --git a/server/src/index.ts b/server/src/index.ts
index a9016b3bb..14803c93b 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -586,19 +586,6 @@ const start = async () => {
}
});
}
-
- // if (process.env.NODE_ENV === "production") {
- // // Initialize uptime monitoring service in the background (non-blocking)
- // uptimeService
- // .initialize()
- // .then(() => {
- // server.log.info("Uptime monitoring service initialized successfully");
- // })
- // .catch((error) => {
- // server.log.error("Failed to initialize uptime service:", error);
- // // Continue running without uptime monitoring
- // });
- // }
} catch (err) {
server.log.error(err);
process.exit(1);
@@ -630,10 +617,6 @@ const shutdown = async (signal: string) => {
await server.close();
server.log.info("Server closed");
- // Shutdown uptime service
- // await uptimeService.shutdown();
- // server.log.info("Uptime service shut down");
-
// Clear the timeout since we're done
clearTimeout(forceExitTimeout);
diff --git a/server/src/lib/twilio.ts b/server/src/lib/twilio.ts
deleted file mode 100644
index 5ea818ebe..000000000
--- a/server/src/lib/twilio.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import twilio from "twilio";
-import { IS_CLOUD } from "./const.js";
-import { createServiceLogger } from "./logger/logger.js";
-
-const logger = createServiceLogger("twilio");
-
-let twilioClient: ReturnType<typeof twilio> | undefined;
-
-// Initialize Twilio client only if we have the necessary credentials
-if (IS_CLOUD && process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
- twilioClient = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
-}
-
-export const sendSMS = async (phoneNumber: string, message: string): Promise<{ success: boolean; error?: string }> => {
- if (!twilioClient) {
- logger.info("Twilio client not initialized - skipping SMS notification");
- return { success: false, error: "SMS not configured" };
- }
-
- if (!process.env.TWILIO_PHONE_NUMBER) {
- logger.error("TWILIO_PHONE_NUMBER not configured");
- return { success: false, error: "SMS sender not configured" };
- }
-
- try {
- const result = await twilioClient.messages.create({
- body: message,
- from: process.env.TWILIO_PHONE_NUMBER,
- to: phoneNumber,
- });
-
- logger.info({ messageId: result.sid }, "Successfully sent SMS");
- return { success: true };
- } catch (error) {
- logger.error({ err: error }, "Failed to send SMS");
- return {
- success: false,
- error: error instanceof Error ? error.message : "Failed to send SMS",
- };
- }
-};
-
-export const isSMSConfigured = (): boolean => {
- return !!(
- twilioClient &&
- process.env.TWILIO_PHONE_NUMBER &&
- process.env.TWILIO_ACCOUNT_SID &&
- process.env.TWILIO_AUTH_TOKEN
- );
-};
diff --git a/server/src/services/tracker/botBlocking/referrerSpam.ts b/server/src/services/tracker/botBlocking/referrerSpam.ts
deleted file mode 100644
index 152206cba..000000000
--- a/server/src/services/tracker/botBlocking/referrerSpam.ts
+++ /dev/null
@@ -1,645 +0,0 @@
-/**
- * Generated by server/src/services/tracker/botBlocking/update-referrer-spam.mjs.
- *
- * Source: matomo-org/referrer-spam-list spammers.txt
- * URL: https://raw.githubusercontent.com/matomo-org/referrer-spam-list/master/spammers.txt
- * Generated: 2026-05-19
- *
- * Do not edit the domain list by hand. Re-run:
- * npm run update:referrer-spam
- */
-
-export const REFERRER_SPAM_SOURCE = {
- name: "matomo-org/referrer-spam-list",
- url: "https://raw.githubusercontent.com/matomo-org/referrer-spam-list/master/spammers.txt",
- generatedAt: "2026-05-19",
-} as const;
-
-const REFERRER_SPAM_LIST: readonly string[] = [
- "0-0.fr", "007agent-i.fr", "01casino-x.ru", "033nachtvandeliteratuur.nl",
- "03e.info", "03p.info", "0n-line.tv", "1-88.vip",
- "1-99seo.com", "1-best-seo.com", "1-free-share-buttons.com", "100-reasons-for-seo.com",
- "100dollars-seo.com", "12-reasons-for-seo.net", "12masterov.com", "12u.info",
- "15-reasons-for-seo.com", "16lv.com", "1kreditzaim.ru", "1pamm.ru",
- "1st-urist.ru", "1webmaster.ml", "1wek.top", "1winru.ru",
- "1x-slot.site", "1x-slots.site", "1xbet-entry.ru", "1xbetcc.com",
- "1xbetonlines1.ru", "1xbetportugal.com", "1xbetts.ru", "1xslot-casino.online",
- "1xslot-casino.ru", "1xslot-casino.site", "1xslot.site", "1xslots-africa.site",
- "1xslots-brasil.site", "1xslots-casino.site", "1xslots.africa", "1xslots.site",
- "2-best-seo.com", "2-easy.xyz", "2-go-now.xyz", "24h.doctor",
- "24x7-server-support.site", "2your.site", "3-best-seo.com", "3-letter-domains.net",
- "3dgame3d.com", "3waynetworks.com", "4-best-seo.com", "40momporntube.com",
- "4inn.ru", "4ip.su", "4istoshop.com", "4webmasters.org",
- "4xcasino.ru", "5-best-seo.com", "5-steps-to-start-business.com", "5elementov.ru",
- "5forex.ru", "6-best-seo.com", "69-13-59.ru", "6hopping.com",
- "7-best-seo.com", "70casino.online", "7kop.ru", "7makemoneyonline.com",
- "7milliondollars.com", "7ooo.ru", "7zap.com", "8-best-seo.com",
- "84lv.com", "8xv8.com", "9-best-seo.com", "99-reasons-for-seo.com",
- "a-elita.in.ua", "abacoasale.xyz", "abaiak.com", "abcdefh.xyz",
- "abcdeg.xyz", "abclauncher.com", "abuser.shop", "acads.net",
- "acarreo.ru", "account-my1.xyz", "accs-store.ru", "actualremont.ru",
- "acunetix-referrer.com", "adanih.com", "adcash.com", "adelachrist.top",
- "adf.ly", "adpostmalta.com", "adrenalinebot.net", "adrenalinebot.ru",
- "adspart.com", "adtiger.tk", "adult-video-chat.ru", "adventureparkcostarica.com",
- "advertisefree.co.uk", "adviceforum.info", "advokateg.xyz", "aerodizain.com",
- "aerotour.ru", "affiliate-programs.biz", "affordablewebsitesandmobileapps.com", "afora.ru",
- "afshan.shop", "agro-gid.com", "agtl.com.ua", "ahecmarket.xyz",
- "ahhjf.com", "ai-seo-services.com", "aibolita.com", "aidarmebel.kz",
- "aimeesblog.xyz", "aimiot.net", "aio.online", "aitiman.ae",
- "akmussale.xyz", "akuhni.by", "albuteroli.com", "alcobutik24.com",
- "alertomall.xyz", "alexsander.ch", "alfabot.xyz", "alguiblog.online",
- "alibestsale.com", "aliexsale.ru", "alinabaniecka.pl", "aliviahome.online",
- "alkanfarma.org", "all-news.kz", "all4bath.ru", "allcryptonews.com",
- "allergick.com", "allergija.com", "allfan.ru", "allknow.info",
- "allmarketsnewdayli.gdn", "allnews.md", "allnews24.in", "allproblog.com",
- "allvacancy.ru", "allwomen.info", "allwrighter.ru", "alma-mramor.com.ua",
- "alp-rk.ru", "alphaopt24.ru", "alpharma.net", "altermix.ua",
- "amatocanizalez.net", "amazon-seo-service.com", "amos-kids.ru", "amp-project.pro",
- "amt-k.ru", "amtel-vredestein.com", "amylynnandrews.xyz", "anabolics.shop",
- "analytics-ads.xyz", "ananumous.ru", "anapa-inns.ru", "andrewancheta.com",
- "android-style.com", "animalphotos.xyz", "animenime.ru", "annaeydlish.top",
- "anrtmall.xyz", "anti-crisis-seo.com", "anticrawler.org", "antiguabarbuda.ru",
- "antonovich-design.com.ua", "anydesk.site", "aoul.top", "apilian.xyz",
- "apollon-market-url.org", "applepharma.ru", "apteka-doc.ru", "apteka-pharm.ru",
- "apteka.info", "arabic-poetry.com", "arcarticle.online", "arendadogovor.ru",
- "arendakvartir.kz", "arendovalka.xyz", "argo-visa.ru", "arkansale.xyz",
- "arkkivoltti.net", "armetsrcu.asia", "arpe.top", "artblog.top",
- "artclipart.ru", "artdeko.info", "artpaint-market.ru", "artparquet.ru",
- "artpress.top", "artsmarket.xyz", "arturs.moscow", "aruplighting.com",
- "ascotgoods.xyz", "ask-yug.com", "astimvnc.online", "asupro.com",
- "asynt.net", "aszokshop.xyz", "atleticpharm.org", "atoblog.online",
- "atyks.ru", "aucoinhomes.com", "auto-b2b-seo-service.com", "auto-complex.by",
- "auto-kia-fulldrive.ru", "auto-seo-service.org", "autoblog.org.ua", "autofuct.ru",
- "automobile-spec.com", "autoseo-service.org", "autoseo-traffic.com", "autoseotips.com",
- "autoservic.by", "autovideobroadcast.com", "avcoast.com", "aviaseller.su",
- "aviva-limoux.com", "avkzarabotok.info", "avtointeres.ru", "avtorskoe-vino.ru",
- "avtovykup.kz", "aworlds.com", "axcus.top", "ayongoods.xyz",
- "azartclub.org", "azbukafree.com", "azlex.uz", "baciakte.online",
- "backlinks-fast-top.com", "bahisgunceladresi.com", "baixar-musicas-gratis.com", "baladur.ru",
- "balakhna.online", "balayazh.com", "balitouroffice.com", "balkanfarma.org",
- "bankhummer.co", "barbarahome.top", "bard-real.com.ua", "batietiket.com",
- "batut-fun.ru", "bavariagid.de", "bavsac.com", "bdf-tracker.top",
- "beachtoday.ru", "beauty-lesson.com", "beclean-nn.ru", "bedroomlighting.us",
- "belreferatov.net", "beremenyashka.com", "berglion.com", "berkinan.xyz",
- "best-deal-hdd.pro", "best-mam.ru", "best-ping-service-usa.blue", "best-printmsk.ru",
- "best-seo-offer.com", "best-seo-software.xyz", "best-seo-solution.com", "bestbookclub.ru",
- "bestfortraders.com", "besthatcheries.com", "bestmobilityscooterstoday.com", "bestofferhddbyt.info",
- "bestofferhddeed.info", "bestvpnrating.com", "bestwebsitesawards.com", "bet-winner1.ru",
- "bet2much.ru", "betslive.ru", "betterhealthbeauty.com", "bettorschool.ru",
- "bez-zabora.ru", "bezprostatita.com", "bhf.vc", "bibprsale.xyz",
- "bif-ru.info", "biglistofwebsites.com", "billiard-classic.com.ua", "billyblog.online",
- "bin-brokers.com", "binokna.ru", "bio-market.kz", "biplanecentre.ru",
- "bird1.ru", "bitcoin-ua.top", "biteg.xyz", "bitniex.com",
- "biz-law.ru", "bizru.info", "bki24.info", "black-friday.ga",
- "black-tip.top", "blackhatworth.com", "blancablog.online", "blockchaintop.nl",
- "blog.xsk.in", "blog100.org", "blog2019.top", "blog2019.xyz",
- "blog4u.top", "blogking.top", "bloglag.com", "blognet.top",
- "blogorganictraffic.shop", "blogseo.xyz", "blogstar.fun", "blogtotal.de",
- "blogtraffic.shop", "blogua.org", "blue-square.biz", "bluerobot.info",
- "bmusshop.xyz", "bo-vtb24.ru", "boltalko.xyz", "boltushkiclub.ru",
- "bonkers.name", "bonniesblog.online", "bonus-betting.ru", "bonus-spasibo-sberbank.ru",
- "bonus-vtb.ru", "books-top.com", "boost24.biz", "boostmyppc.com",
- "bostonline.xyz", "bot-traffic.icu", "bot-traffic.xyz", "botamycos.fr",
- "bottraffic.live", "bottraffic143.xyz", "bottraffic329.xyz", "bottraffic4free.club",
- "bottraffic4free.host", "bottraffic999.xyz", "bowigosale.xyz", "bpro1.top",
- "bradleylive.xyz", "brakehawk.com", "brandnewtube.com", "brateg.xyz",
- "brauni.com.ua", "bravica.biz", "bravica.com", "bravica.me",
- "bravica.net", "bravica.news", "bravica.online", "bravica.pro",
- "bravica.ru", "bravica.su", "break-the-chains.com", "briankatrine.top",
- "brickmaster.pro", "brillianty.info", "britneyblog.online", "brk-rti.ru",
- "brooklynsays.com", "brothers-smaller.ru", "brusilov.ru", "bsell.ru",
- "btcnix.com", "btt-club.pro", "budilneg.xyz", "budmavtomatika.com.ua",
- "bufetout.ru", "buhproffi.ru", "buildnw.ru", "buildwithwendy.com",
- "buketeg.xyz", "bukleteg.xyz", "bulgaria-web-developers.com", "bur-rk.ru",
- "burger-imperia.com", "burn-fat.ga", "business-online-sberbank.ru", "buttons-for-website.com",
- "buttons-for-your-website.com", "buy-cheap-online.info", "buy-cheap-pills-order-online.com", "buy-forum.ru",
- "buy-meds24.com", "buynorxx.com", "buypillsonline24h.com", "buypuppies.ca",
- "c2bit.hk", "call-of-duty.info", "cancerfungus.com", "candida-society.org.uk",
- "cannazon-market.org", "carder.me", "carder.tv", "carders.ug",
- "cardiosport.com.ua", "cardsdumps.com", "carezi.com", "carivka.com.ua",
- "carscrim.com", "cartechnic.ru", "cashforum.cc", "casino-top3.fun",
- "casino-top3.online", "casino-top3.ru", "casino-top3.site", "casino-top3.space",
- "casino-top3.website", "casino-v.site", "casino-vulkane.com", "casino-x-now.ru",
- "casino-x.host", "casinosbewertung.de", "casinox-jp.com", "catherinemill.xyz",
- "catterybengal.com", "cattyhealth.com", "cauxmall.xyz", "cazino-v.online",
- "cazino-v.ru", "ccfullzshop.com", "celestepage.xyz", "cenokos.ru",
- "cenoval.ru", "certifywebsite.win", "cezartabac.ro", "chainii.ru",
- "chatmall.xyz", "chatrazvrat.ru", "chatroulette.life", "chcu.net",
- "cheap-trusted-backlinks.com", "cheapkeys.ovh", "cheappills24h.com", "chinese-amezon.com",
- "chip35.ru", "chipmp3.ru", "chizhik-2.ru", "chomexun.com",
- "ci.ua", "ciarustde.online", "cilolamall.xyz", "cityadspix.com",
- "citybur.ru", "cityreys.ru", "civilwartheater.com", "cleandom.in.ua",
- "clicksor.com", "climate.by", "clothing-deal.club", "club-lukojl.ru",
- "cmrrsale.xyz", "cmseshop.xyz", "coderstate.com", "codysbbq.com",
- "coeus-solutions.de", "coffeemashiny.ru", "coinswitch.cash", "coleso.md",
- "collectinviolity.com", "columb.net.ua", "commentag.com", "commerage.ru",
- "comp-pomosch.ru", "compliance-alex.xyz", "compliance-alexa.xyz", "compliance-andrew.xyz",
- "compliance-barak.xyz", "compliance-brian.xyz", "compliance-don.xyz", "compliance-donald.xyz",
- "compliance-elena.xyz", "compliance-fred.xyz", "compliance-george.xyz", "compliance-irvin.xyz",
- "compliance-ivan.xyz", "compliance-john.top", "compliance-julianna.top", "computer-remont.ru",
- "comuneshop.xyz", "conciergegroup.org", "concretepol.com", "connectikastudio.com",
- "constanceonline.top", "cookie-law-enforcement-aa.xyz", "cookie-law-enforcement-bb.xyz", "cookie-law-enforcement-cc.xyz",
- "cookie-law-enforcement-dd.xyz", "cookie-law-enforcement-ee.xyz", "cookie-law-enforcement-ff.xyz", "cookie-law-enforcement-gg.xyz",
- "cookie-law-enforcement-hh.xyz", "cookie-law-enforcement-ii.xyz", "cookie-law-enforcement-jj.xyz", "cookie-law-enforcement-kk.xyz",
- "cookie-law-enforcement-ll.xyz", "cookie-law-enforcement-mm.xyz", "cookie-law-enforcement-nn.xyz", "cookie-law-enforcement-oo.xyz",
- "cookie-law-enforcement-pp.xyz", "cookie-law-enforcement-qq.xyz", "cookie-law-enforcement-rr.xyz", "cookie-law-enforcement-ss.xyz",
- "cookie-law-enforcement-tt.xyz", "cookie-law-enforcement-uu.xyz", "cookie-law-enforcement-vv.xyz", "cookie-law-enforcement-ww.xyz",
- "cookie-law-enforcement-xx.xyz", "cookie-law-enforcement-yy.xyz", "cookie-law-enforcement-zz.xyz", "cool-mining.com",
- "copyrightclaims.org", "copyrightinstitute.org", "coral-info.com", "cosmediqueresults.com",
- "covadhosting.biz", "covblog.top", "coverage-my.com", "covid-schutzmasken.de",
- "cp24.com.ua", "cpnbshop.xyz", "crazy-mining.org", "credit-card-tinkoff.ru",
- "credit-cards-online24.ru", "credit.co.ua", "crypto-bear.com", "crypto-bears.com",
- "crypto-mining.club", "crypto-wallets.org", "crypto1x1.com", "curenaturalicancro.com",
- "curenaturalicancro.nl", "customsua.com.ua", "cvta.xyz", "cyber-monday.ga",
- "czcedu.com", "dacha-svoimi-rukami.com", "dailyblog.xyz", "dailyrank.net",
- "dailyseo.xyz", "dailystorm.ru", "damianis.ru", "danhale.xyz",
- "darcysassoon.top", "darknet-hydra-onion.biz", "darknet.sb", "darknetsitesguide.com",
- "darleneblog.online", "darodar.com", "dav.kz", "davilaonline.shop",
- "dawlenie.com", "dbutton.net", "dcdcapital.com", "deart-13.ru",
- "deirdre.top", "delfin-aqua.com.ua", "delo.fund", "deluxewatch.su",
- "demenageur.com", "dengi-v-kredit.in.ua", "denisecarey.top", "deniseconnie.top",
- "dent-home.ru", "dentuled.net", "dermatovenerologiya.com", "deryie.com",
- "descargar-musica-gratis.net", "detailedvideos.com", "detoolzon.xyz", "detskie-konstruktory.ru",
- "deutsche-poesie.com", "dev-seo.blog", "devochki-video.ru", "dezeypmall.xyz",
- "dgdsoutlet.xyz", "diatelier.ru", "dicru.info", "dienai.ru",
- "dienmaytot.xyz", "diplomas-ru.com", "dipstar.org", "discounttaxi.kz",
- "distonija.com", "divan-dekor.com.ua", "dividendo.ru", "djekxa.ru",
- "djonwatch.ru", "dktr.ru", "dldsshop.xyz", "dna-sklad.ru",
- "dnmetall.ru", "docs4all.com", "docsarchive.net", "docsportal.net",
- "doctmalls.xyz", "doctornadezhda.ru", "documentbase.net", "documentserver.net",
- "documentsite.net", "dodge-forum.eu", "doggyhealthy.com", "dogovorpodryada.ru",
- "dogsrun.net", "dojki-devki.ru", "dojki-hd.com", "dom-international.ru",
- "domain-tracker.com", "domashniy-hotel.ru", "domashniy-recepti.ru", "dominateforex.ml",
- "domination.ml", "dommdom.com", "domovozik.ru", "dompechey.by",
- "domsadiogorod.ru", "doreenblog.online", "doska-vsem.ru", "dostavka-v-krym.com",
- "dosugrostov.site", "doxyporno.com", "doxysexy.com", "draniki.org",
- "dreamland-bg.com", "dreams-works.net", "drev.biz", "drugs-no-rx.info",
- "drugstoreforyou.com", "drupa.com", "dspautomations.com", "duitbux.info",
- "dumpsccshop.com", "dvk-stroi.ru", "dvr.biz.ua", "dzinerstudio.com",
- "e-buyeasy.com", "e-commerce-seo.com", "e-commerce-seo1.com", "e-stroymart.kz",
- "eaptekaplus.ru", "earn-from-articles.com", "earnian-money.info", "easycommerce.cf",
- "eavuinsr.online", "ecblog.xyz", "ecommerce-seo.org", "ecomp3.ru",
- "econom.co", "edakgfvwql.ru", "edmed-sonline.com", "ednetstore.xyz",
- "eduardoluis.com", "educhess.ru", "edudocs.net", "eduinfosite.com",
- "eduserver.net", "eecz.org", "eets.net", "ege-essay.ru",
- "ege-krasnoyarsk.ru", "egovaleo.it", "ek-invest.ru", "ekatalog.xyz",
- "ekbspravka.ru", "eko-gazon.ru", "ekoproekt-kr.ru", "ekto.ee",
- "elainasblog.xyz", "eldoradorent.az", "electric-blue-industries.com", "elegante-vitrage.ru",
- "elektrikovich.ru", "elementspluss.ru", "elenatkachenko.com.ua", "elentur.com.ua",
- "elizabethbruno.top", "ellemarket.com", "elmifarhangi.com", "elvel.com.ua",
- "emctestlab.ru", "emerson-rus.ru", "emicef.com", "empire-market.org",
- "empire-market.xyz", "empiremarket-link.org", "empiremarketlink24.com", "empirestuff.org",
- "encmbtia.online", "energomash.net", "energysexy.com", "englishtopic.ru",
- "enter-unicredit.ru", "envistore.xyz", "epcpolo.com", "epicdiving.com",
- "eraglass.com", "erias.xyz", "eric-artem.com", "ericshome.store",
- "erinhome.xyz", "ero-video-chat.org", "erofus.online", "eropho.com",
- "eropho.net", "erot.co", "erotag.com", "eroticheskij-video-chat.ru",
- "es-pfrf.ru", "escort-russian.com", "eskei83.com", "esoterikforum.at",
- "essaytags.com", "estdj.com", "este-line.com.ua", "etairikavideo.gr",
- "etehnika.com.ua", "etotupo.ru", "ets-2-mod.ru", "etsfshop.xyz",
- "eu-cookie-law-enforcement2.xyz", "eurocredit.xyz", "euromasterclass.ru", "europages.com.ru",
- "eurosamodelki.ru", "event-tracking.com", "eventiyahall.ru", "evreuxshop.xyz",
- "exclusive-profit.com", "exdocsfiles.com", "execedmall.xyz", "exotic-video-chat.ru",
- "expediacustomerservicenumber.online", "expert-find.ru", "express-vyvoz.ru", "eyes-on-you.ga",
- "f1nder.org", "fainaidea.com", "faithe.top", "falco3d.com",
- "falcoware.com", "fanoboi.com", "fartunabest.ru", "fashiong.ru",
- "fast-wordpress-start.com", "fastgg.net", "fatrizscae.online", "favoritki-msk.ru",
- "fazika.ru", "fbdownloader.com", "feiacmr.shop", "feminist.org.ua",
- "fidalsa.de", "fierrohack.ru", "figensahin.com", "filesclub.net",
- "filesdatabase.net", "films2018.com", "filter-ot-zheleza.ru", "financial-simulation.com",
- "finansov.info", "finder.cool", "findercarphotos.com", "fineblog.top",
- "firmgeo.xyz", "firstblog.top", "fit-discount.ru", "fitodar.com.ua",
- "fiuagts.online", "fix-website-errors.com", "flexderek.com", "floating-share-buttons.com",
- "flowertherapy.ru", "flyblog.xyz", "foojo.net", "for-marketersy.info",
- "for-your.website", "forex-procto.ru", "forsex.info", "fortwosmartcar.pw",
- "forum69.info", "foxweber.com", "fpclub.ru", "francaise-poesie.com",
- "frankofficial.ru", "frauplus.ru", "free-fb-traffic.com", "free-fbook-traffic.com",
- "free-floating-buttons.com", "free-games-download.falcoware.com", "free-share-buttons.com", "free-social-buttons.com",
- "free-social-buttons.xyz", "free-social-buttons7.xyz", "free-traffic.xyz", "free-video-chat.ru",
- "free-video-tool.com", "free-website-traffic.com", "freenode.info", "freewhatsappload.com",
- "freewlan.info", "freshnails.com.ua", "fsalas.com", "fsin-pokypka.ru",
- "fullzdumps.cc", "furniturehomewares.com", "fvetgoods.xyz", "galblog.top",
- "gamblingpp.ru", "game300.ru", "gammatraffic.com", "gandikapper.ru",
- "gaokr.xyz", "garantprava.com", "gasvleningrade.ru", "gatwick.ru",
- "gays-video-chat.ru", "gazel-72.ru", "gbh-invest.ru", "gcmx.net",
- "gearcraft.us", "gearsadspromo.club", "geliyballon.ru", "gelstate.ru",
- "generalporn.org", "geniusfood.co.uk", "georgeblog.online", "gepatit-info.top",
- "germes-trans.com", "get-clickize.info", "get-free-social-traffic.com", "get-free-traffic-now.com",
- "get-more-freeer-visitors.info", "get-more-freeish-visitors.info", "get-seo-help.com", "get-your-social-buttons.info",
- "getaadsincome.info", "getadsincomely.info", "getbottraffic4free.xyz", "getfy-click.info",
- "getlamborghini.ga", "getpy-click.info", "getrichquick.ml", "getrichquickly.info",
- "gevciamst.online", "gezlev.com.ua", "ghazel.ru", "ghostvisitor.com",
- "gidonline.one", "gidro-partner.ru", "giftbig.ru", "girlporn.ru",
- "gk-casino.fun", "gk-casino.online", "gk-casino.ru", "gk-casino.site",
- "gk-casino.space", "gk-casino.website", "gkvector.ru", "glavprofit.ru",
- "glktfw.net", "global-smm.ru", "gobongo.info", "golden-praga.ru",
- "goldvaultmetals.com", "golyedevushki.com", "good-potolok.ru", "goodbyecellulite.ru",
- "goodcoffeepremium.com", "goodhumor24.com", "goodprotein.ru", "google-liar.ru",
- "googlemare.com", "googlsucks.com", "gorgaz.info", "goyua.xyz",
- "graceonline.shop", "grafaman.ru", "greatblog.top", "greentechsy.com",
- "groshi-kredut.com.ua", "growth-hackingan.info", "growth-hackingor.info", "growth-hackingy.info",
- "gruzchiki24.ru", "gttpsale.xyz", "guardlink.org", "guidetopetersburg.com",
- "gxcb.net", "hagirkblog.space", "halat.xyz", "halefa.com",
- "hamyshop.xyz", "handicapvantoday.com", "hankspring.xyz", "happysong.ru",
- "hard-porn.mobi", "hardosale.xyz", "harpro.net", "havepussy.com",
- "hawaiisurf.com", "hd1080film.ru", "hdhc.site", "hdmoviecamera.net",
- "hdmoviecams.com", "hdsmartvideoreg.ru", "headpharmacy.com", "healbio.ru",
- "healgastro.com", "healthhacks.ru", "heeha.net", "hentai-manga.porn",
- "heroero.com", "hexometer.com", "hilaryblog.top", "himandmall.xyz",
- "hit-kino.ru", "hitree.shop", "hiwpro.xyz", "hkjrsale.xyz",
- "holiday-shop.ru", "holistickenko.com", "holodkovich.com", "homeafrikalike.tk",
- "homemypicture.tk", "hongfanji.com", "hostiman.ru", "hosting-tracker.com",
- "hotblognetwork.com", "hottour.com", "housedesigning.ru", "housediz.com",
- "housemilan.ru", "howopen.ru", "howtostopreferralspam.eu", "hoztorg-opt.ru",
- "hrtonline.xyz", "hseipaa.kz", "hsoutdoor.com", "hugblog.xyz",
- "hulfingtonpost.com", "humanorightswatch.org", "hundejo.com", "huntdown.info",
- "hvd-store.com", "hydra-2019.ru", "hydra-2020.online", "hydra-2020.ru",
- "hydra-centr.fun", "hydra-dealer.com", "hydra-guide.org", "hydra-new.online",
- "hydra-onion-faq.com", "hydra-pc.com", "hydra-shop.org", "hydra-site.ru",
- "hydra-slon.net", "hydra-vhod2020.com", "hydra-zerkalo20.com", "hydra.online",
- "hydra1717.com", "hydra2.market", "hydra2020.top", "hydra2020gate.com",
- "hydra2020market.com", "hydra2020onion.com", "hydra2020ru.com", "hydra2020zerkala.com",
- "hydra2020zerkalo.com", "hydra20onion.com", "hydra20online.com", "hydra20original.com",
- "hydra2use.com", "hydra2zahod.com", "hydraena.com", "hydrahow.com",
- "hydrahudra.com", "hydraland.net", "hydramarket2020.com", "hydramirror2020.com",
- "hydranten.net", "hydraonion2019.net", "hydrarusmarket.com", "hydraruz-2020.com",
- "hydraruzonion2020.com", "hydraruzonionx.ru", "hydraruzxpnew4af.com.co", "hydraruzxpnew4af.ink",
- "hydraruzxpnew4aff.ru", "hydraruzxpwnew4afonion.com", "hydraulicoilcooler.net", "hydrauliczny.com",
- "hydravizoficial.info", "hydrazerkalo2019.net", "hydrazerkalo2020.com", "hyip-zanoza.me",
- "i-spare.ru", "ialgramer.shop", "ib-homecredit.ru", "ib-rencredit.ru",
- "iblogpress.xyz", "iceton.net", "ico.re", "ideayz.com",
- "ieamblog.online", "ieeeoutlet.xyz", "ierblog.xyz", "igadgetsworld.com",
- "igamingtop.com", "igru-xbox.net", "ilikevitaly.com", "iloveitaly.ro",
- "iloveitaly.ru", "ilovevitaly.co", "ilovevitaly.com", "ilovevitaly.info",
- "ilovevitaly.org", "ilovevitaly.ru", "ilovevitaly.xyz", "iminent.com",
- "immigrational.info", "immobilieralgerie.net", "imperiafilm.ru", "impotentik.com",
- "in-mostbet.ru", "in-sto.ru", "incanto.in.ua", "incitystroy.ru",
- "incomekey.net", "incoonline.xyz", "increasewwwtraffic.info", "inet-shop.su",
- "infektsii.com", "infodocsportal.com", "infogame.name", "inform-ua.info",
- "ingramreed.xyz", "inmoll.com", "insider.pro", "installspartners.com",
- "instasexyblog.com", "insultu-net.ru", "interferencer.ru", "intex-air.ru",
- "intimchats.ru", "investpamm.ru", "iridsale.xyz", "iskalko.ru",
- "iskussnica.ru", "isotoner.com", "ispaniya-costa-blanca.ru", "it-max.com.ua",
- "it-worlds.com", "iuyun.net", "iyfsearch.com", "izamorfix.ru",
- "izhevskjob.xyz", "izhstrelok.ru", "izi24.ru", "jabug.xyz",
- "jacblog.xyz", "jackonline.store", "janemill.xyz", "jariblog.online",
- "jav-fetish.com", "jav-fetish.site", "jav-idol.com", "javcoast.com",
- "javlibrary.cc", "jeffbullas.xyz", "jikem.com", "jintub.com",
- "jjbabskoe.ru", "job-opros.ru", "job-prosto.ru", "jobgirl24.ru",
- "jobius.com.ua", "johnnyhaley.top", "josephineblog.top", "joyceblog.top",
- "joycee.xyz", "judyandsimon.com", "jumkite.com", "justkillingti.me",
- "justprofit.xyz", "jweber.ru", "jyrxd.com", "kabbalah-red-bracelets.com",
- "kabinet-5ka.ru", "kabinet-alfaclick.ru", "kabinet-binbank.ru", "kabinet-card-5ka.ru",
- "kabinet-click-alfabank.ru", "kabinet-esia-gosuslugi.ru", "kabinet-faberlic.ru", "kabinet-gosuslugi.ru",
- "kabinet-ipoteka-domclick.ru", "kabinet-karta-5ka.ru", "kabinet-lk-megafon.ru", "kabinet-lk-rt.ru",
- "kabinet-login-mts.ru", "kabinet-mil.ru", "kabinet-mos.ru", "kabinet-my-beeline.ru",
- "kabinet-my-pochtabank.ru", "kabinet-nalog.ru", "kabinet-online-bm.ru", "kabinet-online-open.ru",
- "kabinet-online-rsb.ru", "kabinet-online-rshb.ru", "kabinet-online-sberbank.ru", "kabinet-online-sovcombank.ru",
- "kabinet-online-vtb.ru", "kabinet-pfr.ru", "kabinet-pfrf.ru", "kabinet-platon.ru",
- "kabinet-qiwi.ru", "kabinet-tele2.ru", "kabinet-tinkoff.ru", "kabinet-tricolor.ru",
- "kabinet-ttk.ru", "kabinet-vtb24.ru", "kaegtcr.online", "kaircm.shop",
- "kakablog.net", "kakadu-interior.com.ua", "kakworldoftanks.ru", "kambasoft.com",
- "kamin-sam.ru", "kanakox.com", "karapuz.org.ua", "katrd.xyz",
- "kazka.ru", "kazlenta.kz", "kazrent.com", "kellyonline.xyz",
- "kendrablog.online", "kenyagoods.xyz", "kerch.site", "kevblog.top",
- "kevinsnow.online", "kexihao.xyz", "keywords-monitoring-success.com", "keywords-monitoring-your-success.com",
- "kharkov.ua", "kierowca-praca.pl", "kimblog.top", "kinnarimasajes.com",
- "kino-fun.ru", "kino-key.info", "kino2018.cc", "kinobum.org",
- "kinopolet.net", "kinosed.net", "kinostar.online", "kiyany-za-spravedluvist.com.ua",
- "klfd.net", "knigonosha.net", "kolcasale.xyz", "kollekcioner.ru",
- "komp-pomosch.ru", "komputers-best.ru", "komukc.com.ua", "konkursov.net",
- "kosunnyclub.com", "kozhakoshek.com", "kozhasobak.com", "kozhniebolezni.com",
- "kpcconline.xyz", "krasivoe-hd.net", "krasnodar-avtolombard.ru", "krasota-zdorovie.pw",
- "krasota.ru", "kredutu.com.ua", "kredytbank.com.ua", "kruiz-sochi.ru",
- "krumble-adsde.info", "krumble-adsen.info", "krumbleent-ads.info", "kursy-ege.ru",
- "l2soft.eu", "labguamec.online", "lafppshop.xyz", "laitrcus.online",
- "lakiikraski.ru", "lalalove.ru", "lambreshop.xyz", "laminat.com.ua",
- "landliver.org", "landoftracking.com", "laptop-4-less.com", "law-check-two.xyz",
- "law-enforcement-bot-ff.xyz", "law-enforcement-check-three.xyz", "law-enforcement-ee.xyz", "law-six.xyz",
- "lawrenceblog.online", "laxdrills.com", "lcecshop.xyz", "lcgrm.com",
- "leboard.ru", "lebowmall.xyz", "ledalfa.by", "leddjc.net",
- "ledx.by", "leeboyrussia.com", "legalrc.biz", "leon-official.site",
- "lerporn.info", "leto-dacha.ru", "lider82.ru", "lifespeaker.ru",
- "ligastavok-in.ru", "lighthearteds.shop", "lindsayblog.online", "lipidofobia.com.br",
- "littleberry.ru", "live-xbet.com", "livefixer.com", "livejournal.top",
- "livia-pache.ru", "livingroomdecoratingideas.website", "livingsimply.com", "lk-gosuslugi.ru",
- "lk-lk-rt.ru", "local-seo-for-multiple-locations.com", "login-tinkoff.ru", "logo-all.ru",
- "lolz.guru", "lolzteam.online", "lolzteam.org", "lookover.ru",
- "lotoflotto.ru", "loveorganic.ch", "lowpricesiterx.com", "lsex.xyz",
- "lsitenonrepeat.com", "luckybull.io", "lukoilcard.ru", "lumb.co",
- "luton-invest.ru", "luxup.ru", "luxurybet.ru", "lyckants.online",
- "madisonclothingny.com", "madjonline.xyz", "magicart.store", "magicdiet.gq",
- "magnetic-bracelets.ru", "maigralr.site", "mainhunter.com", "makemoneyonline.com",
- "makeprogress.ga", "makler.org.ua", "malbgoods.xyz", "maltadailypost.com",
- "mamidushop.xyz", "mamylik.ru", "manimpotence.com", "manonstore.xyz",
- "manwang.net", "maofengjx.com", "marathonbet-in.ru", "marblestyle.ru",
- "maridan.com.ua", "marihome.online", "marjorieblog.online", "marketland.ml",
- "martinahome.xyz", "masterseek.com", "mathoutlet.xyz", "matomete.net",
- "matras.space", "mattgibson.us", "max-apprais.com", "maxinesamson.top",
- "maxxximoda.ru", "mebel-arts.com", "mebel-ekb.com", "mebel-iz-dereva.kiev.ua",
- "mebelcomplekt.ru", "mebeldekor.com.ua", "meblieco.com", "med-dopomoga.com",
- "med-recept.ru", "med-zdorovie.com.ua", "medbrowse.info", "medcor-list.ru",
- "medic-al.ru", "medicaltranslate.ru", "medicineseasybuy.com", "meds-online24.com",
- "meduza-consult.ru", "megalit-d.ru", "megapolis-96.ru", "megatkani.ru",
- "melbet-in.ru", "melissahome.top", "mercanmall.xyz", "meriton.ru",
- "meroyharte.top", "metallo-konstruktsii.ru", "metallosajding.ru", "meteocast.net",
- "meuikcr.online", "mhp.su", "mhrdmall.xyz", "miaxxx.com",
- "michellblog.online", "midnight.im", "mifepriston.net", "migronis.com",
- "mikozstop.com", "mikrocement.com.ua", "mikrozaim.site", "mikrozaym2you.ru",
- "minegam.com", "minghaimuyuan.net", "miningblack.net", "mirfairytale.ru",
- "mirobuvi.com.ua", "mirtorrent.net", "misselle.ru", "mksoap.ru",
- "mksport.ru", "mmdoors.ru", "mmm.lc", "mmm.sb",
- "mnogabukaff.net", "mobicover.com.ua", "mobilemedia.md", "mobisport.ru",
- "mockupui.com", "modforwot.ru", "modnie-futbolki.net", "moe1.ru",
- "moinozhki.com", "moiragracie.top", "moisadogorod.ru", "monetizationking.net",
- "money-for-placing-articles.com", "money7777.info", "moneytop.ru", "moneyzzz.ru",
- "monicablog.xyz", "moon.market", "moonci.ru", "mosputana.info",
- "mosputana.top", "mosrif.ru", "mossiemckenzie.shop", "mostbet-285.com",
- "mostbet-original.ru", "mostcool.top", "mostorgnerud.ru", "moy-dokument.com",
- "moy-evroopt.ru", "moyakuhnia.ru", "moyaskidka.ru", "moygorod-online.ru",
- "moyparnik.com", "mrbojikobi4.biz", "mrt-info.ru", "msk-sprawka.com",
- "mtras.xyz", "mtsguru.ru", "mukis.ru", "muscle-factory.com.ua",
- "musichallaudio.ru", "mvmagoods.xyz", "mwductwork.com", "mybestoffers.club",
- "myborder.ru", "mybuh.kz", "mycheaptraffic.com", "mycollegereview.com",
- "mydirtystuff.com", "mydoctorok.ru", "myecomir.com", "myftpupload.com",
- "myplaycity.com", "mysexpics.ru", "mytherealshop.com", "mytraffic.shop",
- "nachalka21.ru", "nakozhe.com", "nancyblog.top", "nanochskazki.ru",
- "nanwar.xyz", "naobumium.info", "naphi.xyz", "narkomaniya-stop.ru",
- "narosty.com", "natali-forex.com", "natprof.ru", "naturalpharm.com.ua",
- "navek.by", "nbok.net", "nebbiasale.xyz", "needtosellmyhousefast.com",
- "net-profits.xyz", "nethouse.ru", "nevapotolok.ru", "newagebev.com",
- "newbieseoblog.online", "newsfj.net", "newsrosprom.ru", "newstaffadsshop.club",
- "nfocusdriver.com", "nhmrcsale.xyz", "nicola.top", "nicolaonline.top",
- "niki-mlt.ru", "ninacecillia.top", "niuting.org", "no-rx.info",
- "nomerounddec.cf", "novalskincare.net", "novosti-avto.ru", "novosti-hi-tech.ru",
- "novostic.ru", "now-hydra2020.com", "nsujfo.com", "ntdtv.ru",
- "nubuilderian.info", "nufaq.com", "nutriwestncahi.com", "nvkzsale.xyz",
- "nwrcz.com", "nyinfo.org", "o-o-11-o-o.com", "o-o-6-o-o.com",
- "o-o-6-o-o.ru", "o-o-8-o-o.com", "o-o-8-o-o.ru", "o-promyshlennosti.ru",
- "oblismall.xyz", "obnallpro.cc", "obsessionphrases.com", "obyavka.org.ua",
- "obzor-casino-x.online", "obzor-casino-x.ru", "odiabetikah.com", "odsadsmobile.biz",
- "ofermerah.com", "office2web.com", "officedocuments.net", "ogorodnic.com",
- "okna-systems.pro", "okno.ooo", "okoshkah.com", "oledonline.xyz",
- "olovoley.ru", "omega.best", "one-a-plus.xyz", "onenews24.ru",
- "onion20hydra.ru", "onionhydra.net", "onionshydra.com", "online-akbars.ru",
- "online-binbank.ru", "online-hit.info", "online-intim.com", "online-mkb.ru",
- "online-pharma.ru", "online-pochtabank.ru", "online-raiffeisen.ru", "online-sbank.ru",
- "online-templatestore.com", "online-video-chat.ru", "online-vostbank.ru", "online-vtb.ru",
- "onlinedic.net", "onlinetvseries.me", "onlinewot.ru", "onlywoman.org",
- "oohlivecams.com", "ooo-olni.ru", "oooh.pro", "optsol.ru",
- "oqex.io", "oracle-patches.ru", "orakul.spb.ru", "osteochondrosis.ru",
- "otdbiaxaem-vmeste.ru", "otdyx-s-komfortom.ru", "oudallas.net", "own-ahrefs.com",
- "ownshop.cf", "ozas.net", "pacobarrero.com", "pageinsider.org",
- "paidonlinesites.com", "painting-planet.com", "palma-de-sochi.ru", "palvira.com.ua",
- "pamjatnik.com.ua", "pamyatnik-spb.ru", "pamyatnik-tsena.ru", "pandoshop.xyz",
- "parcsmalls.xyz", "paretto.ru", "parking-invest.ru", "partizan19.ru",
- "partnerskie-programmy.net", "patonsale.xyz", "paulinho.ru", "pay.ru",
- "pc-services.ru", "pecmastore.xyz", "penzu.xyz", "perform-like-alibabaity.info",
- "perform-likeism-alibaba.info", "perimetor.ru", "perm.dienai.ru", "perper.ru",
- "petrovka-online.com", "petrushka-restoran.ru", "petscar.ru", "pfrf-kabinet.ru",
- "pharm--shop.ru", "phimarshcer.online", "phimmakinhdi.com", "photo-clip.ru",
- "photokitchendesign.com", "php-market.ru", "picturesmania.com", "pills24h.com",
- "piluli.info", "pinupcasinos.ru", "pinupcasinos1.ru", "pinupp1.com",
- "piratbike.ru", "pirelli-matador.ru", "piulatte.cz", "pizdeishn.com",
- "pizdeishn.net", "pizza-imperia.com", "pizza-tycoon.com", "pk-pomosch.ru",
- "pk-services.ru", "plagscan.com", "podarkilove.ru", "poddon-moskva.ru",
- "podemnik.pro", "podseka1.ru", "poiskzakona.ru", "poker-royal777.com",
- "pokupaylegko.ru", "polemikon.ru", "politika.bg", "polyana-skazok.org.ua",
- "popads.net", "popelina.com", "pops.foundation", "popugauka.ru",
- "popugaychiki.com", "porn-video-chat.ru", "porndl.org", "pornhive.org",
- "pornhub-forum.ga", "pornhub-ru.com", "porno-asia.com", "porno-chaman.info",
- "porno-gallery.ru", "porno2xl.net", "pornobest.su", "pornoelita.info",
- "pornoforadult.com", "pornofoto.org", "pornogig.com", "pornohd1080.online",
- "pornoklad.ru", "pornonik.com", "pornoplen.com", "pornorasskazy.net",
- "pornosemki.info", "pornoslave.net", "portnoff.od.ua", "pospektr.ru",
- "posteezy.xyz", "potolokelekor.ru", "povodok-shop.ru", "pozdravleniya-c.ru",
- "predmety.in.ua", "prezidentshop.ru", "priceg.com", "pricheski-video.com",
- "primfootball.com", "primoblog.xyz", "print-technology.ru", "private-service.best",
- "prizesk.com", "prizrn.site", "prlog.ru", "probenzo.com.ua",
- "procrafts.ru", "prodaemdveri.com", "producm.ru", "prodvigator.ua",
- "professionalsolutions.eu", "profnastil-moscow.ru", "progressive-seo.com", "prointer.net.ua",
- "prom23.ru", "promoforum.ru", "promoteapps.online", "promotion-for99.com",
- "pron.pro", "proquoshop.xyz", "prosmibank.ru", "prostitutki-rostova.ru.com",
- "prostoacc.com", "psa48.ru", "psiosale.xyz", "psn-card.ru",
- "ptashkatextil.ua", "ptfic.org", "punch.media", "purchasepillsnorx.com",
- "puzzleweb.ru", "qiwi.xyz", "qoinex.top", "qtrstar.xyz",
- "qualitymarketzone.com", "quickchange.cc", "quit-smoking.ga", "qwesa.ru",
- "qxnr.net", "rachelblog.online", "rainbirds.ru", "rangjued.com",
- "rank-checker.online", "rankings-analytics.com", "ranksonic.info", "ranksonic.net",
- "ranksonic.org", "rapidgator-porn.ga", "rapidhits.net", "rapidsites.pro",
- "raschtextil.com.ua", "ratraiser.online", "raymondblog.top", "razborka-skoda.org.ua",
- "rb-str.ru", "rcb101.ru", "rczhan.com", "realresultslist.com",
- "recinziireale.com", "rednise.com", "redraincine.com", "refpawro.xyz",
- "reginablog.top", "reginanahum.top", "regionshop.biz", "reklamnoe.agency",
- "releshop.ru", "rembash.ru", "remkompov.ru", "remont-kvartirspb.com",
- "remontvau.ru", "rent2spb.ru", "replica-watch.ru", "research.ifmo.ru",
- "resell-seo-services.com", "resellerclub.com", "residualforlife.com", "responsive-test.net",
- "resurs-2012.ru", "reversing.cc", "revolgc.pro", "rfavon.ru",
- "rfesc.net", "riedismall.xyz", "rightenergysolutions.com.au", "rkmbonline.xyz",
- "robocheck.info", "roof-city.ru", "room-mebel.ru", "rospromtest.ru",
- "royal-casino.online", "royal-casino.ru", "royal-casinos.online", "royal-casinos.ru",
- "royal-cazino.online", "royal-cazino.ru", "rrutw.com", "rspectr.com",
- "ru-lk-rt.ru", "ru-onion.com", "ru-online-sberbank.ru", "rufreechats.com",
- "ruhydraru.ru", "ruinfocomp.ru", "rulate.ru", "rumamba.com",
- "runetki-online.net", "rupolitshow.ru", "rus-lit.com", "ruscams-com.ru",
- "rusexy.xyz", "ruspoety.ru", "russian-postindex.ru", "russian-translator.com",
- "russian-videochats.ru", "russkie-sochineniya.ru", "rustag.ru", "rutor.group",
- "rxshop.md", "rybalka-opt.ru", "s-forum.biz", "s-luna.me",
- "sabinablog.xyz", "sad-torg.com.ua", "sady-urala.ru", "saltspray.ru",
- "samanthablog.online", "samara-airport.com", "samara-comfort.ru", "samchist.ru",
- "samlaurabrown.top", "samogonius.ru", "sanjosestartups.com", "santaren.by",
- "santasgift.ml", "santehnovich.ru", "sapaship.ru", "sarahmilne.top",
- "saudegoods.xyz", "sauna-v-ufe.ru", "sauni-lipetsk.ru", "sauni-moskva.ru",
- "savetubevideo.com", "savetubevideo.info", "scansafe.net", "scat.porn",
- "sciedsale.xyz", "screen-led.ru", "screentoolkit.com", "scripted.com",
- "search-error.com", "searchencrypt.com", "security-corporation.com.ua", "seekanvdoo22.live",
- "seisasale.xyz", "sel-hoz.com", "selfhotdog.com", "sell-fb-group-here.com",
- "semalt.com", "semalt.net", "semaltmedia.com", "semxiu.com",
- "senacertificados.co", "seo-2-0.com", "seo-platform.com", "seo-services-b2b.com",
- "seo-services-wordpress.com", "seo-smm.kz", "seo-tips.top", "seo-traffic.xyz",
- "seoanalyses.com", "seobook.top", "seocheckupx.com", "seocheckupx.net",
- "seoexperimenty.ru", "seojokes.net", "seopub.net", "seoriseome.netlify.app",
- "seoservices2018.com", "serenamall.xyz", "serialsx.ru", "servemlixo.xyz",
- "sex-porno.site", "sex-spying.ru", "sex-videochats.ru", "sexpornotales.net",
- "sexreliz.com", "sexreliz.net", "sexsaoy.com", "sexuria.net",
- "sexwife.net", "sexy-girl-chat.ru", "sexyali.com", "shagtomsk.ru",
- "shamcisale.xyz", "shanscasino1.ru", "share-buttons-for-free.com", "share-buttons.xyz",
- "sharebutton.io", "sharebutton.net", "sharebutton.to", "shcrose.com",
- "sheki-spb.ru", "shisenshop.xyz", "shnyagi.net", "shop-garena.ru",
- "shop.garena.ru.com", "shop2hydra.com", "shop4fit.ru", "shopfishing.com.ua",
- "shoppinglocation.com", "shoppingmiracles.co.uk", "shoprybalka.ru", "shops-ru.ru",
- "shopsellcardsdumps.com", "shsupplychain.com", "shtaketniki.ru", "shtormmall.xyz",
- "shulepov.ru", "sib-kukla.ru", "sibecoprom.ru", "sibkukla.ru",
- "sign-service.ru", "sihugoods.xyz", "silvergull.ru", "sim-dealer.ru",
- "similarmoviesdb.com", "simoncinicancertherapy.com", "simple-share-buttons.com", "singularwebs.net",
- "sinhronperevod.ru", "sirhoutlet.xyz", "siritshop.xyz", "site-auditor.online",
- "site5.com", "siteripz.net", "sitesadd.com", "sitevaluation.org",
- "sjmsw.net", "skidku.org.ua", "skinali.com", "skinali.photo-clip.ru",
- "sladkoevideo.com", "slashpet.com", "sledstvie-veli.net", "slftsdybbg.ru",
- "slkrm.ru", "slomm.ru", "sloopyjoes.com.top", "slotron.com",
- "slow-website.xyz", "smailik.org", "smartphonediscount.info", "smt4.ru",
- "smzt.shop", "snabs.kz", "snaiper-bg.net", "sneakerfreaker.com",
- "snegozaderzhatel.ru", "snip.to", "snip.tw", "soaksoak.ru",
- "sochi-3d.ru", "social-button.xyz", "social-buttons-ii.xyz", "social-buttons.com",
- "social-traffic-1.xyz", "social-traffic-2.xyz", "social-traffic-3.xyz", "social-traffic-4.xyz",
- "social-traffic-5.xyz", "social-traffic-7.xyz", "social-widget.xyz", "socialbuttons.xyz",
- "socialine.net", "socialseet.ru", "socialtrade.biz", "sohoindia.net",
- "solartek.ru", "solitaire-game.ru", "solnplast.ru", "sosdepotdebilan.com",
- "souvenirua.com", "sovetogorod.ru", "sovetskie-plakaty.ru", "sowhoz.ru",
- "soyuzexpedition.ru", "sp-laptop.ru", "sp-zakupki.ru", "space2019.top",
- "spain-poetry.com", "spartania.com.ua", "spb-plitka.ru", "spb-scenar.ru",
- "specstroy36.ru", "speedup-my.site", "spin2016.cf", "sportobzori.ru",
- "sportwizard.ru", "spravka130.ru", "spravkavspb.net", "spravkavspb.work",
- "sprawka-help.com", "spscmall.xyz", "spy-app.info", "sqadia.com",
- "squarespace.top", "sribno.net", "ssn.is", "sssexxx.net",
- "ssve.ru", "st-komf.ru", "sta-grand.ru", "startraffic.online",
- "stat.lviv.ua", "statashop.xyz", "stavimdveri.ru", "steame.ru",
- "stiralkovich.ru", "stocktwists.com", "stoletie.ru", "stoliar.org",
- "stomatologi.moscow", "stop-nark.ru", "stop-zavisimost.com", "store-rx.com",
- "strady.org.ua", "stream-tds.com", "stroi-24.ru", "strongtools.ga",
- "stroy-matrix.ru", "stroyalp.ru", "stroyka-gid.ru", "stroyka47.ru",
- "studentguide.ru", "stuffhydra.com", "stylecaster.top", "su1ufa.ru",
- "success-seo.com", "suckoutlet.xyz", "sudachitravel.com", "sundrugstore.com",
- "super-seo-guru.com", "superiends.org", "supermama.top", "supermodni.com.ua",
- "superoboi.com.ua", "superslots-casino.online", "superslots-casino.site", "superslots-cazino.online",
- "superslots-cazino.site", "superslotz-casino.site", "superslotz-cazino.site", "supertraffic.xyz",
- "supervesti.ru", "suzanneboswell.top", "svadba-teplohod.ru", "svarog-jez.com",
- "svensk-poesi.com", "svet-depo.ru", "svetka.info", "svetoch.moscow",
- "svoimi-rukamy.com", "svs-avto.com", "swaplab.io", "sweet.tv",
- "t-machinery.ru", "t-rec.su", "taartstore.xyz", "tagmeanvice.live",
- "taihouse.ru", "tam-gde-more.ru", "tamada69.com", "tammyblog.online",
- "targetpay.nl", "tattoo-stickers.ru", "tattooha.com", "tccp.xyz",
- "tcenavoprosa.ru", "tcsinksale.xyz", "tcyh.net", "td-abs.ru",
- "td-l-market.ru", "td-perimetr.ru", "tdbatik.com", "tds-west.ru",
- "technika-remont.ru", "tedxrj.com", "telfer.ru", "teman.com.ua",
- "tennis-bet.ru", "tentcomplekt.ru", "teplohod-gnezdo.ru", "teplokomplex.ru",
- "terapist.xyz", "teresablog.top", "tesla-audit.ru", "texnika.com.ua",
- "tgsubs.com", "tgtclick.com", "thaimassage-slon.ru", "thaoduoctoc.com",
- "the-world.ru", "theautoprofit.ml", "thegreensociety.net", "theguardlan.com",
- "thelotter.su", "therealshop.exaccess.com", "thesensehousehotel.com", "thesmartsearch.net",
- "timmy.by", "tip8.co", "tocan.biz", "tocan.com.ua",
- "tokshow.online", "tomck.com", "tommysautomotivecare.com", "top-gan.ru",
- "top-instagram.info", "top-kasyna.com", "top-l2.com", "top1-seo-service.com",
- "top10-online-games.com", "top10-way.com", "top8.co", "topgurudeals.com",
- "topmebeltorg.ru", "toposvita.com", "topquality.cf", "topseoservices.co",
- "tor.vc", "torobrand.com", "torospa.ru", "torrentgamer.net",
- "torrentred.games", "totppgoods.xyz", "tourburlington.com", "track-rankings.online",
- "tracker24-gps.ru", "trade365.org", "traderzplanet.co.in", "trafers.com",
- "traffic-cash.xyz", "traffic2cash.org", "traffic2cash.xyz", "traffic2money.com",
- "trafficbot.life", "trafficbot4free.xyz", "trafficdrive.club", "trafficgenius.xyz",
- "trafficmonetize.org", "trafficmonetizer.org", "trafficstudio.club", "transit.in.ua",
- "transsex-videochat.ru", "traphouselatino.net", "travel-semantics.com", "travgoods.xyz",
- "trex-casino.com", "trex.casino", "tricolortv-online.com", "trieste.io",
- "trion.od.ua", "truebeauty.cc", "tsatu.edu.ua", "tsc-koleso.ru",
- "ttechno.net", "tudusale.xyz", "tuningdom.ru", "tvfru.org",
- "twsufa.ru", "ua.tc", "uaecdsale.xyz", "uasb.ru",
- "ucanfly.ru", "ucban.xyz", "ucoz.ru", "ucsfstore.xyz",
- "uctraffic.com", "udav.net", "ufolabs.net", "uginekologa.com",
- "ukrainian-poetry.com", "ukrcargo.com", "ukrtvory.in.ua", "ukstmalls.xyz",
- "ul-potolki.ru", "umatrcs.online", "undergroundcityphoto.com", "unibus.su",
- "uniqgen.net", "univerfiles.com", "unlimitdocs.net", "unpredictable.ga",
- "upcronline.xyz", "uptime-as.net", "uptime-eu.net", "uptime-us.net",
- "uptimechecker.com", "urbanblog.shop", "urbanchr.online", "urblog.xyz",
- "urlumbrella.com", "uruto.ru", "uslugi-tatarstan.ru", "uterkysale.xyz",
- "uusmsale.xyz", "uyut-dom.pro", "uyutmaster73.ru", "uzpaket.com",
- "uzungil.com", "v-casino.fun", "v-casino.host", "v-casino.ru",
- "v-casino.site", "v-casino.website", "v-casino.xyz", "v-cazino.online",
- "v-cazino.ru", "vaderenergy.ru", "valid-cc.com", "validccseller.com",
- "validus.pro", "vanessablog.online", "vape-x.ru", "vardenafil20.com",
- "varikozdok.ru", "vavada-casino.host", "vavada-casino.top", "vavada-cazino.host",
- "vavada-cazino.site", "vbikse.com", "vchulkah.net", "veles.shop",
- "veloland.in.ua", "ventopt.by", "veronicablog.top", "vescenter.ru",
- "veselokloun.ru", "vesnatehno.com", "vetbvc.ru", "vezdevoz.com.ua",
- "vgoloveboli.net", "viagra-soft.ru", "video--production.com", "video-girl-online.ru",
- "video-woman.com", "videochat-dating.ru", "videochat.guru", "videochat.world",
- "videos-for-your-business.com", "videotop.biz", "vidzwap.xyz", "viel.su",
- "viktoria-center.ru", "virtchats.ru", "virtual-love-video.ru", "virtual-sex-chat.ru",
- "virtual-sex-time.ru", "virtual-sex-videochat.ru", "virtual-zaim.ru", "virtualbb.com",
- "virus-schutzmasken.de", "vkonche.com", "vksex.ru", "vladtime.ru",
- "vodabur.by", "vodaodessa.com", "vodkoved.ru", "volond.com",
- "vpdr.pl", "vrazbor59.ru", "vrnhnmall.xyz", "vsdelke.ru",
- "vseigru.one", "vseigry.fun", "vseprobrak.ru", "vulkan-nadengi.ru",
- "vulkan-oficial.com", "vulkanrussia1.ru", "vzheludke.com", "vzubah.com",
- "vzube.com", "vzubkah.com", "w2mobile-za.com", "w3javascript.com",
- "wakeupseoconsultant.com", "wallabag.malooma.bzh", "wallet-prlzn.space", "wallinside.top",
- "wallpaperdesk.info", "wallpapers-all.com", "wallstore.xyz", "wandamary.online",
- "warmex.com.ua", "wasabisale.xyz", "wave-games.ru", "wayfcoin.space",
- "wbjm.net", "wdss.com.ua", "we-ping-for-youic.info", "web-analytics.date",
- "web-revenue.xyz", "webalex.pro", "weblibrary.win", "webmaster-traffic.com",
- "webmonetizer.net", "website-analytics.online", "website-analyzer.info", "website-speed-check.site",
- "website-speed-checker.site", "websitebottraffic.host", "websites-reviews.com", "websocial.me",
- "weburlopener.com", "weightbelts.ru", "wfdesigngroup.com", "wjxmenye.com",
- "wmasterlead.com", "woman-orgasm.ru", "wordpress-crew.net", "wordpresscore.com",
- "workius.ru", "workona.com", "works.if.ua", "worldgamenews.com",
- "worldmed.info", "worldofbtc.com", "wpnull.org", "wptraffic.xyz",
- "wrc-info.ru", "wufak.com", "ww2awards.info", "www-lk-rt.ru",
- "x-lime.com", "x-lime.net", "x5market.ru", "xaker26.net",
- "xexe.club", "xion.cash", "xkaz.org", "xmnb.net",
- "xn-------53dbcapga5atlplfdm6ag1ab1bvehl0b7toa0k.xn--p1ai", "xn------6cdbciescapvf0a8bibwx0a1bu.xn--90ais", "xn-----6kcacs9ajdmhcwdcbwwcnbgd13a.xn--p1ai", "xn-----6kcamwewcd9bayelq.xn--p1ai",
- "xn-----7kcaaxchbbmgncr7chzy0k0hk.xn--p1ai", "xn-----clckdac3bsfgdft3aebjp5etek.xn--p1ai", "xn----7sbabb9a1b7bddgm6a1i.xn--p1ai", "xn----7sbabhjc3ccc5aggbzfmfi.xn--p1ai",
- "xn----7sbabhv4abd8aih6bb7k.xn--p1ai", "xn----7sbabm1ahc4b2aqff.su", "xn----7sbabn5abjehfwi8bj.xn--p1ai", "xn----7sbbpe3afguye.xn--p1ai",
- "xn----7sbho2agebbhlivy.xn--p1ai", "xn----8sbaki4azawu5b.xn--p1ai", "xn----8sbarihbihxpxqgaf0g1e.xn--80adxhks", "xn----8sbbjimdeyfsi.xn--p1ai",
- "xn----8sbhefaln6acifdaon5c6f4axh.xn--p1ai", "xn----8sblgmbj1a1bk8l.xn----161-4vemb6cjl7anbaea3afninj.xn--p1ai", "xn----8sbowe2akbcd4h.xn--p1ai", "xn----8sbpmgeilbd8achi0c.xn--p1ai",
- "xn----btbdvdh4aafrfciljm6k.xn--p1ai", "xn----ctbbcjd3dbsehgi.xn--p1ai", "xn----ctbfcdjl8baejhfb1oh.xn--p1ai", "xn----ctbigni3aj4h.xn--p1ai",
- "xn----dtbffp5aagjgfm.xn--p1ai", "xn----ftbeoaiyg1ak1cb7d.xn--p1ai", "xn----itbbudqejbfpg3l.com", "xn----jtbjfcbdfr0afji4m.xn--p1ai",
- "xn--78-6kc6akkhn3a3k.xn--p1ai", "xn--78-6kcmzqfpcb1amd1q.xn--p1ai", "xn--80aaajkrncdlqdh6ane8t.xn--p1ai", "xn--80aabcsc3bqirlt.xn--p1ai",
- "xn--80aanaardaperhcem4a6i.com", "xn--80adaggc5bdhlfamsfdij4p7b.xn--p1ai", "xn--80adgcaax6acohn6r.xn--p1ai", "xn--80aeb6argv.xn--p1ai",
- "xn--80aebzmbfeebe.xn--p1ai", "xn--80ahdheogk5l.xn--p1ai", "xn--90acenikpebbdd4f6d.xn--p1ai", "xn--90acjmaltae3acm.xn--p1acf",
- "xn--b1adccayqiirhu.xn--p1ai", "xn--c1acygb.xn--p1ai", "xn--d1abj0abs9d.in.ua", "xn--d1aifoe0a9a.top",
- "xn--e1aaajzchnkg.ru.com", "xn--e1aahcgdjkg4aeje6j.kz", "xn--e1agf4c.xn--80adxhks", "xpert.com.ua",
- "xrp-ripple.info", "xtraffic.plus", "xtrafficplus.com", "xtrafficplus.online",
- "xtrafficplus.shop", "xtrafficplus.xyz", "xxxhamster.me", "xxxvideochat.ru",
- "xz618.com", "yaderenergy.ru", "yes-com.com", "yes-do-now.com",
- "yhirurga.ru", "ykecwqlixx.ru", "yodse.io", "yoga4.ru",
- "yougame.biz", "youhack.info", "youporn-forum.ga", "youporn-ru.com",
- "your-good-links.com", "your-tales.ru", "yourserverisdown.com", "yourtraffic.club",
- "yqpc.net", "yur-p.ru", "yurcons.pro", "yuristproffi.ru",
- "zagadki.in.ua", "zahodi2hydra.net", "zahvat.ru", "zakaznoy.com.ua",
- "zakis-azota24.ru", "zakisazota-official.com", "zamolotkom.ru", "zapnado.ru",
- "zarabotat-v-internete.biz", "zastroyka.org", "zavod-gm.ru", "zdm-auto.com",
- "zdm-auto.ru", "zdorovie-nogi.info", "zelena-mriya.com.ua", "zexhgoods.xyz",
- "zhcsapp.net", "zhoobintravel.com", "zonefiles.bid", "zot.moscow",
- "zsio.net", "zt-m.ru", "zvetki.ru", "zvooq.eu",
- "zvuker.net",
-];
-
-export const REFERRER_SPAM_COUNT = REFERRER_SPAM_LIST.length;
-
-export const REFERRER_SPAM_DOMAINS: ReadonlySet<string> = new Set(REFERRER_SPAM_LIST);
-
-/**
- * Extract a lowercase hostname from a referrer value. Accepts either a full
- * URL ("https://example.com/path") or a bare host ("example.com"). Returns
- * null if no host can be extracted.
- */
-function extractHost(referrer: string): string | null {
- const trimmed = referrer.trim().toLowerCase();
- if (trimmed.length === 0) return null;
- try {
- return new URL(trimmed).hostname || null;
- } catch {
- // Not a full URL β€” treat as bare host.
- const host = trimmed.replace(/^https?:\/\//, "").split("/")[0].split(":")[0];
- return host || null;
- }
-}
-
-/**
- * Check whether a referrer value is from a known spam domain. Matches the
- * exact hostname and any subdomain of a listed host (e.g. "promo.semalt.com"
- * matches "semalt.com").
- */
-export function isReferrerSpam(referrer: string | null | undefined): boolean {
- if (typeof referrer !== "string") return false;
- const host = extractHost(referrer);
- if (!host) return false;
- if (REFERRER_SPAM_DOMAINS.has(host)) return true;
- // Match parent domains: walk up labels until we find a match or run out.
- let dotIndex = host.indexOf(".");
- while (dotIndex >= 0) {
- const parent = host.slice(dotIndex + 1);
- if (REFERRER_SPAM_DOMAINS.has(parent)) return true;
- dotIndex = host.indexOf(".", dotIndex + 1);
- }
- return false;
-}
diff --git a/server/src/services/tracker/botBlocking/update-referrer-spam.mjs b/server/src/services/tracker/botBlocking/update-referrer-spam.mjs
deleted file mode 100644
index 9a3116a54..000000000
--- a/server/src/services/tracker/botBlocking/update-referrer-spam.mjs
+++ /dev/null
@@ -1,121 +0,0 @@
-import { readFile, writeFile } from "node:fs/promises";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const SOURCE_URL =
- process.env.REFERRER_SPAM_URL ??
- "https://raw.githubusercontent.com/matomo-org/referrer-spam-list/master/spammers.txt";
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const outputPath = path.resolve(__dirname, "referrerSpam.ts");
-
-async function loadSource() {
- const localPath = process.argv[2];
- if (localPath) {
- return readFile(localPath, "utf8");
- }
-
- const response = await fetch(SOURCE_URL);
- if (!response.ok) {
- throw new Error(`Failed to fetch ${SOURCE_URL}: ${response.status} ${response.statusText}`);
- }
- return response.text();
-}
-
-function uniqueSortedDomains(text) {
- const domains = new Set();
- for (const rawLine of text.split(/\r?\n/)) {
- const line = rawLine.trim().toLowerCase();
- if (!line || line.startsWith("#")) continue;
- // Strip any accidental scheme / path / port the upstream list might pick up.
- const withoutScheme = line.replace(/^https?:\/\//, "");
- const host = withoutScheme.split("/")[0].split(":")[0].trim();
- if (host.length === 0) continue;
- domains.add(host);
- }
- return [...domains].sort();
-}
-
-function formatDomainList(domains) {
- const lines = [];
- for (let i = 0; i < domains.length; i += 4) {
- const chunk = domains.slice(i, i + 4).map(d => JSON.stringify(d));
- lines.push(` ${chunk.join(", ")},`);
- }
- return lines.join("\n");
-}
-
-function render(domains) {
- const generatedAt = new Date().toISOString().slice(0, 10);
- return `/**
- * Generated by server/src/services/tracker/botBlocking/update-referrer-spam.mjs.
- *
- * Source: matomo-org/referrer-spam-list spammers.txt
- * URL: ${SOURCE_URL}
- * Generated: ${generatedAt}
- *
- * Do not edit the domain list by hand. Re-run:
- * npm run update:referrer-spam
- */
-
-export const REFERRER_SPAM_SOURCE = {
- name: "matomo-org/referrer-spam-list",
- url: "${SOURCE_URL}",
- generatedAt: "${generatedAt}",
-} as const;
-
-const REFERRER_SPAM_LIST: readonly string[] = [
-${formatDomainList(domains)}
-];
-
-export const REFERRER_SPAM_COUNT = REFERRER_SPAM_LIST.length;
-
-export const REFERRER_SPAM_DOMAINS: ReadonlySet<string> = new Set(REFERRER_SPAM_LIST);
-
-/**
- * Extract a lowercase hostname from a referrer value. Accepts either a full
- * URL ("https://example.com/path") or a bare host ("example.com"). Returns
- * null if no host can be extracted.
- */
-function extractHost(referrer: string): string | null {
- const trimmed = referrer.trim().toLowerCase();
- if (trimmed.length === 0) return null;
- try {
- return new URL(trimmed).hostname || null;
- } catch {
- // Not a full URL β€” treat as bare host.
- const host = trimmed.replace(/^https?:\\/\\//, "").split("/")[0].split(":")[0];
- return host || null;
- }
-}
-
-/**
- * Check whether a referrer value is from a known spam domain. Matches the
- * exact hostname and any subdomain of a listed host (e.g. "promo.semalt.com"
- * matches "semalt.com").
- */
-export function isReferrerSpam(referrer: string | null | undefined): boolean {
- if (typeof referrer !== "string") return false;
- const host = extractHost(referrer);
- if (!host) return false;
- if (REFERRER_SPAM_DOMAINS.has(host)) return true;
- // Match parent domains: walk up labels until we find a match or run out.
- let dotIndex = host.indexOf(".");
- while (dotIndex >= 0) {
- const parent = host.slice(dotIndex + 1);
- if (REFERRER_SPAM_DOMAINS.has(parent)) return true;
- dotIndex = host.indexOf(".", dotIndex + 1);
- }
- return false;
-}
-`;
-}
-
-const source = await loadSource();
-const domains = uniqueSortedDomains(source);
-if (domains.length < 500) {
- throw new Error(`Refusing to write suspiciously small referrer spam list (${domains.length} entries)`);
-}
-
-await writeFile(outputPath, render(domains));
-console.log(`Wrote ${domains.length} referrer spam domains to ${path.relative(process.cwd(), outputPath)}`);
diff --git a/server/src/services/tracker/const.ts b/server/src/services/tracker/const.ts
index 9d4c7e1d6..67a6eaff2 100644
--- a/server/src/services/tracker/const.ts
+++ b/server/src/services/tracker/const.ts
@@ -1,9 +1,3 @@
-/**
- * Set to true to disable origin checking for tracking requests
- * This should only be enabled in development or testing environments
- */
-export const DISABLE_ORIGIN_CHECK = process.env.DISABLE_ORIGIN_CHECK === "true";
-
const searchDomains = [
// Google and variants
"google.com",
diff --git a/server/src/services/uptime/checks/httpCheck.ts b/server/src/services/uptime/checks/httpCheck.ts
deleted file mode 100644
index 03c68d861..000000000
--- a/server/src/services/uptime/checks/httpCheck.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { request } from "undici";
-import { performance } from "perf_hooks";
-import dns from "dns/promises";
-import { HttpCheckResult } from "../types.js";
-
-interface HttpCheckOptions {
- url: string;
- method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";
- headers?: Record<string, string>;
- body?: string;
- auth?: {
- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";
- credentials?: {
- username?: string;
- password?: string;
- token?: string;
- headerName?: string;
- headerValue?: string;
- };
- };
- followRedirects?: boolean;
- timeoutMs?: number;
- ipVersion?: "any" | "ipv4" | "ipv6";
- userAgent?: string;
-}
-
-export async function performHttpCheck(options: HttpCheckOptions): Promise<HttpCheckResult> {
- const startTime = performance.now();
- const timing = {
- dnsMs: 0,
- tcpMs: 0,
- tlsMs: 0,
- ttfbMs: 0,
- transferMs: 0,
- };
-
- try {
- // Parse URL
- const url = new URL(options.url);
-
- // DNS lookup timing
- const dnsStart = performance.now();
- try {
- const dnsOptions: any = {};
- if (options.ipVersion === "ipv4") dnsOptions.family = 4;
- if (options.ipVersion === "ipv6") dnsOptions.family = 6;
-
- await dns.lookup(url.hostname, dnsOptions);
- timing.dnsMs = Math.round(performance.now() - dnsStart);
- } catch (error) {
- throw {
- message: `DNS lookup failed: ${error instanceof Error ? error.message : "Unknown error"}`,
- type: "dns_failure",
- };
- }
-
- // Prepare headers
- const headers: Record<string, string> = {
- "User-Agent": options.userAgent || "Rybbit-Uptime-Monitor/1.0",
- ...options.headers,
- };
-
- // Add authentication
- if (options.auth && options.auth.type !== "none") {
- switch (options.auth.type) {
- case "basic":
- if (options.auth.credentials?.username && options.auth.credentials?.password) {
- const encoded = Buffer.from(
- `${options.auth.credentials.username}:${options.auth.credentials.password}`
- ).toString("base64");
- headers["Authorization"] = `Basic ${encoded}`;
- }
- break;
- case "bearer":
- if (options.auth.credentials?.token) {
- headers["Authorization"] = `Bearer ${options.auth.credentials.token}`;
- }
- break;
- case "api_key":
- case "custom_header":
- if (options.auth.credentials?.headerName && options.auth.credentials?.headerValue) {
- headers[options.auth.credentials.headerName] = options.auth.credentials.headerValue;
- }
- break;
- }
- }
-
- // Perform request
- const requestStart = performance.now();
- const response = await request(options.url, {
- method: options.method,
- headers,
- body: options.body,
- bodyTimeout: options.timeoutMs || 30000,
- headersTimeout: options.timeoutMs || 30000,
- // maxRedirections: options.followRedirects !== false ? 5 : 0,
- });
-
- // Calculate timings
- timing.ttfbMs = Math.round(performance.now() - requestStart);
-
- // Get response body and size
- const transferStart = performance.now();
- const bodyBuffer = await response.body.arrayBuffer();
- const bodySizeBytes = bodyBuffer.byteLength;
-
- timing.transferMs = Math.round(performance.now() - transferStart);
-
- // Estimate TCP and TLS times (these are approximations)
- timing.tcpMs = Math.round((timing.ttfbMs - timing.dnsMs) * 0.3);
- if (url.protocol === "https:") {
- timing.tlsMs = Math.round((timing.ttfbMs - timing.dnsMs - timing.tcpMs) * 0.5);
- }
-
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- // Convert headers to simple object
- const responseHeaders: Record<string, string> = {};
- for (const [key, value] of Object.entries(response.headers)) {
- responseHeaders[key] = Array.isArray(value) ? value.join(", ") : String(value);
- }
-
- return {
- status: "success",
- statusCode: response.statusCode,
- responseTimeMs,
- timing,
- headers: responseHeaders,
- bodySizeBytes,
- validationErrors: [],
- };
- } catch (error: any) {
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- // Handle different error types
- let errorType = "unknown_error";
- let errorMessage = error.message || "Unknown error occurred";
-
- if (error.code === "UND_ERR_CONNECT_TIMEOUT") {
- errorType = "connection_timeout";
- errorMessage = "Connection timed out";
- } else if (error.code === "UND_ERR_HEADERS_TIMEOUT") {
- errorType = "headers_timeout";
- errorMessage = "Headers timeout";
- } else if (error.code === "UND_ERR_BODY_TIMEOUT") {
- errorType = "body_timeout";
- errorMessage = "Body timeout";
- } else if (error.code === "ENOTFOUND") {
- errorType = "dns_failure";
- errorMessage = "DNS lookup failed";
- } else if (error.code === "ECONNREFUSED") {
- errorType = "connection_refused";
- errorMessage = "Connection refused";
- } else if (error.message?.includes("SSL") || error.message?.includes("TLS")) {
- errorType = "ssl_error";
- } else if (error.type) {
- errorType = error.type;
- errorMessage = error.message;
- }
-
- return {
- status: errorType.includes("timeout") ? "timeout" : "failure",
- responseTimeMs,
- timing,
- headers: {},
- bodySizeBytes: 0,
- validationErrors: [],
- error: {
- message: errorMessage,
- type: errorType,
- },
- };
- }
-}
diff --git a/server/src/services/uptime/checks/tcpCheck.ts b/server/src/services/uptime/checks/tcpCheck.ts
deleted file mode 100644
index 2a7846d02..000000000
--- a/server/src/services/uptime/checks/tcpCheck.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import net from "net";
-import { performance } from "perf_hooks";
-import { TcpCheckResult } from "../types.js";
-
-interface TcpCheckOptions {
- host: string;
- port: number;
- timeoutMs?: number;
-}
-
-export async function performTcpCheck(options: TcpCheckOptions): Promise<TcpCheckResult> {
- const startTime = performance.now();
-
- return new Promise<TcpCheckResult>(resolve => {
- const socket = new net.Socket();
- const timeout = options.timeoutMs || 30000;
-
- // Set timeout
- socket.setTimeout(timeout);
-
- // Handle successful connection
- socket.on("connect", () => {
- const responseTimeMs = Math.round(performance.now() - startTime);
- socket.destroy();
-
- resolve({
- status: "success",
- responseTimeMs,
- validationErrors: [],
- });
- });
-
- // Handle errors
- socket.on("error", (error: any) => {
- const responseTimeMs = Math.round(performance.now() - startTime);
- socket.destroy();
-
- let errorType = "connection_error";
- let errorMessage = error.message || "Connection failed";
-
- if (error.code === "ECONNREFUSED") {
- errorType = "connection_refused";
- errorMessage = `Connection refused to ${options.host}:${options.port}`;
- } else if (error.code === "ENOTFOUND") {
- errorType = "dns_failure";
- errorMessage = `Host ${options.host} not found`;
- } else if (error.code === "ETIMEDOUT") {
- errorType = "connection_timeout";
- errorMessage = "Connection timed out";
- } else if (error.code === "EHOSTUNREACH") {
- errorType = "host_unreachable";
- errorMessage = `Host ${options.host} is unreachable`;
- }
-
- resolve({
- status: errorType === "connection_timeout" ? "timeout" : "failure",
- responseTimeMs,
- validationErrors: [],
- error: {
- message: errorMessage,
- type: errorType,
- },
- });
- });
-
- // Handle timeout
- socket.on("timeout", () => {
- const responseTimeMs = Math.round(performance.now() - startTime);
- socket.destroy();
-
- resolve({
- status: "timeout",
- responseTimeMs,
- validationErrors: [],
- error: {
- message: `Connection timeout after ${timeout}ms`,
- type: "connection_timeout",
- },
- });
- });
-
- // Attempt connection
- try {
- socket.connect(options.port, options.host);
- } catch (error: any) {
- const responseTimeMs = Math.round(performance.now() - startTime);
-
- resolve({
- status: "failure",
- responseTimeMs,
- validationErrors: [],
- error: {
- message: error.message || "Failed to initiate connection",
- type: "connection_error",
- },
- });
- }
- });
-}
diff --git a/server/src/services/uptime/monitorExecutor.ts b/server/src/services/uptime/monitorExecutor.ts
deleted file mode 100644
index f1459bf21..000000000
--- a/server/src/services/uptime/monitorExecutor.ts
+++ /dev/null
@@ -1,716 +0,0 @@
-import { Worker, Job } from "bullmq";
-import { eq, and, inArray } from "drizzle-orm";
-import { DateTime } from "luxon";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors, uptimeMonitorStatus, agentRegions, uptimeIncidents } from "../../db/postgres/schema.js";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { MonitorCheckJob, HttpCheckResult, TcpCheckResult, MonitorEvent } from "./types.js";
-import { performHttpCheck } from "./checks/httpCheck.js";
-import { performTcpCheck } from "./checks/tcpCheck.js";
-import { applyValidationRules } from "./validationEngine.js";
-import { NotificationService } from "./notificationService.js";
-import { createServiceLogger } from "../../lib/logger/logger.js";
-
-interface AgentExecuteRequest {
- jobId: string;
- monitorId: number;
- monitorType: string;
- config: any;
- validationRules: any[];
-}
-
-interface AgentExecuteResponse {
- jobId: string;
- region: string;
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- statusCode?: number;
- headers?: Record<string, string>;
- timing?: {
- dnsMs?: number;
- tcpMs?: number;
- tlsMs?: number;
- ttfbMs?: number;
- transferMs?: number;
- };
- error?: {
- message: string;
- type: string;
- };
- validationErrors?: string[];
- bodySizeBytes?: number;
-}
-
-export class MonitorExecutor {
- private worker: Worker | null = null;
- private concurrency: number;
- private isShuttingDown = false;
- private connection: { host: string; port: number; password?: string };
- private notificationService: NotificationService;
- private logger = createServiceLogger("monitor-executor");
-
- // Confirmation thresholds - require multiple consecutive checks before triggering incidents
- private static readonly FAILURE_THRESHOLD = 2; // Consecutive failures before creating incident
- private static readonly SUCCESS_THRESHOLD = 2; // Consecutive successes before resolving incident
-
- constructor(concurrency: number = 10) {
- this.concurrency = concurrency;
- this.connection = {
- host: process.env.REDIS_HOST || "localhost",
- port: parseInt(process.env.REDIS_PORT || "6379", 10),
- ...(process.env.REDIS_PASSWORD && { password: process.env.REDIS_PASSWORD }),
- };
- this.notificationService = new NotificationService();
- }
-
- async start(): Promise<void> {
- this.logger.info({ concurrency: this.concurrency }, "Starting BullMQ monitor executor");
-
- // Create worker to process jobs
- this.worker = new Worker(
- "monitor-checks",
- async (job: Job<MonitorCheckJob>) => {
- await this.processMonitorCheck(job.data);
- },
- {
- connection: this.connection,
- concurrency: this.concurrency,
- autorun: true,
- removeOnComplete: {
- count: 100,
- },
- removeOnFail: {
- count: 100,
- },
- }
- );
-
- // Set up event listeners
- // this.worker.on("completed", (job) => {
- // this.logger.debug(`Job ${job.id} completed successfully`);
- // });
-
- this.worker.on("failed", (job, err) => {
- this.logger.error({ err, jobId: job?.id }, "Monitor job failed");
- });
-
- this.worker.on("error", err => {
- this.logger.error({ err }, "Monitor worker error");
- });
-
- this.worker.on("ready", () => {
- this.logger.info("BullMQ worker is ready and listening for jobs");
- });
-
- // this.worker.on("active", (job) => {
- // this.logger.debug(`Job ${job.id} is now active`);
- // });
-
- // Wait for worker to be ready
- await new Promise<void>(resolve => {
- if (this.worker) {
- this.worker.once("ready", () => {
- resolve();
- });
- }
- });
-
- this.logger.info("BullMQ monitor executor started successfully");
- }
-
- private async processMonitorCheck(jobData: MonitorCheckJob): Promise<void> {
- const { monitorId } = jobData;
-
- try {
- this.logger.debug({ monitorId }, "Processing monitor check");
-
- // Fetch monitor configuration
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, monitorId),
- });
-
- if (!monitor || !monitor.enabled) {
- this.logger.debug({ monitorId }, "Monitor not found or disabled");
- return;
- }
-
- // Check if this is a global monitor
- if (monitor.monitoringType === "global" && monitor.selectedRegions && monitor.selectedRegions.length > 0) {
- await this.processGlobalMonitorCheck(monitor);
- return;
- }
-
- // For local monitoring, proceed with the original logic
- let result: HttpCheckResult | TcpCheckResult;
- let responseBody: string | undefined;
-
- if (monitor.monitorType === "http" && monitor.httpConfig) {
- const httpResult = await performHttpCheck({
- url: monitor.httpConfig.url,
- method: monitor.httpConfig.method || "GET",
- headers: monitor.httpConfig.headers,
- body: monitor.httpConfig.body,
- auth: monitor.httpConfig.auth,
- followRedirects: monitor.httpConfig.followRedirects !== false,
- timeoutMs: monitor.httpConfig.timeoutMs,
- ipVersion: monitor.httpConfig.ipVersion,
- userAgent: monitor.httpConfig.userAgent,
- });
-
- result = httpResult;
-
- // For HTTP checks, we might need the response body for validation
- // Note: In production, you might want to limit body size or make this optional
- if (httpResult.status === "success" && monitor.validationRules.length > 0) {
- // For now, we'll skip body validation to avoid memory issues
- // In a real implementation, you'd stream the body or limit size
- responseBody = undefined;
- }
- } else if (monitor.monitorType === "tcp" && monitor.tcpConfig) {
- result = await performTcpCheck({
- host: monitor.tcpConfig.host,
- port: monitor.tcpConfig.port,
- timeoutMs: monitor.tcpConfig.timeoutMs,
- });
- } else {
- throw new Error(`Invalid monitor configuration for monitor ${monitorId}`);
- }
-
- // Apply validation rules for successful checks
- if (result.status === "success" && monitor.validationRules.length > 0) {
- const validationErrors = applyValidationRules(result as HttpCheckResult, monitor.validationRules, responseBody);
-
- if (validationErrors.length > 0) {
- result.validationErrors = validationErrors;
- // Change status to failure if validation fails
- result.status = "failure";
- }
- }
-
- // Store result in ClickHouse
- await this.storeMonitorEvent(monitor, result);
-
- // Update monitor status in PostgreSQL
- await this.updateMonitorStatus(monitor.id, result);
-
- this.logger.info(
- { monitorId, monitorStatus: result.status, responseTimeMs: result.responseTimeMs },
- "Monitor check completed"
- );
- } catch (error) {
- this.logger.error({ err: error, monitorId }, "Error processing monitor check");
-
- // Try to store the error event
- try {
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, monitorId),
- });
-
- if (monitor) {
- const errorResult: HttpCheckResult = {
- status: "failure",
- responseTimeMs: 0,
- timing: {},
- headers: {},
- bodySizeBytes: 0,
- validationErrors: [],
- error: {
- message: error instanceof Error ? error.message : "Internal error during monitor check",
- type: "internal_error",
- },
- };
-
- await this.storeMonitorEvent(monitor, errorResult);
- await this.updateMonitorStatus(monitor.id, errorResult);
- }
- } catch (innerError) {
- this.logger.error({ err: innerError, monitorId }, "Failed to store monitor error event");
- }
- }
- }
-
- private async processGlobalMonitorCheck(monitor: any): Promise<void> {
- try {
- // Filter to only include non-local regions
- const globalRegions = monitor.selectedRegions.filter((r: string) => r !== "local");
-
- if (globalRegions.length === 0) {
- this.logger.debug({ monitorId: monitor.id }, "Monitor has no global regions selected");
- return;
- }
-
- // Fetch agent regions information
- const regions = await db.query.agentRegions.findMany({
- where: and(
- inArray(agentRegions.code, globalRegions),
- eq(agentRegions.enabled, true),
- eq(agentRegions.isHealthy, true)
- ),
- });
-
- if (regions.length === 0) {
- this.logger.warn({ monitorId: monitor.id }, "No healthy regions found for monitor");
- return;
- }
-
- // Execute checks in parallel across all regions
- const regionPromises = regions.map(region =>
- this.executeAgentCheck(monitor, region).catch(error => {
- this.logger.error(
- { err: error, monitorId: monitor.id, regionCode: region.code },
- "Error executing regional monitor check"
- );
- return {
- region: region.code,
- result: {
- status: "failure" as const,
- responseTimeMs: 0,
- timing: {},
- headers: {},
- bodySizeBytes: 0,
- validationErrors: [],
- error: {
- message: error instanceof Error ? error.message : "Agent communication error",
- type: "agent_error",
- },
- } as HttpCheckResult,
- };
- })
- );
-
- const regionResults = await Promise.all(regionPromises);
-
- // Store results for each region
- for (const { region, result } of regionResults) {
- await this.storeMonitorEvent(monitor, result, region);
- }
-
- // Handle incidents per region with thresholds
- for (const { region, result } of regionResults) {
- await this.handleRegionalIncident(monitor, region, result);
- }
-
- // Update monitor status based on the majority of regions
- const successCount = regionResults.filter(r => r.result.status === "success").length;
- const overallStatus = successCount > regionResults.length / 2 ? "success" : "failure";
-
- // Use the average response time from successful checks
- const successfulResults = regionResults.filter(r => r.result.status === "success");
- const avgResponseTime =
- successfulResults.length > 0
- ? successfulResults.reduce((sum, r) => sum + r.result.responseTimeMs, 0) / successfulResults.length
- : 0;
-
- const aggregatedResult: HttpCheckResult = {
- status: overallStatus === "success" ? "success" : "failure",
- responseTimeMs: avgResponseTime,
- timing: {},
- headers: {},
- bodySizeBytes: 0,
- validationErrors: [],
- };
-
- await this.updateMonitorStatus(monitor.id, aggregatedResult);
-
- this.logger.info(
- { monitorId: monitor.id, monitorStatus: overallStatus, regionCount: regionResults.length },
- "Global monitor check completed"
- );
- } catch (error) {
- this.logger.error({ err: error, monitorId: monitor.id }, "Error processing global monitor check");
- }
- }
-
- private async executeAgentCheck(
- monitor: any,
- region: any
- ): Promise<{ region: string; result: HttpCheckResult | TcpCheckResult }> {
- const jobId = `${monitor.id}-${Date.now()}-${region.code}`;
-
- const request: AgentExecuteRequest = {
- jobId,
- monitorId: monitor.id,
- monitorType: monitor.monitorType,
- config: monitor.monitorType === "http" ? monitor.httpConfig : monitor.tcpConfig,
- validationRules: monitor.validationRules || [],
- };
-
- try {
- const response = await fetch(`${region.endpointUrl}/execute`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(request),
- signal: AbortSignal.timeout(60000), // 60 second timeout
- });
-
- if (!response.ok) {
- throw new Error(`Agent returned status ${response.status}`);
- }
-
- const agentResponse: AgentExecuteResponse = await response.json();
-
- // Convert agent response to our internal format
- const result: HttpCheckResult | TcpCheckResult =
- monitor.monitorType === "http"
- ? {
- status: agentResponse.status,
- statusCode: agentResponse.statusCode,
- responseTimeMs: agentResponse.responseTimeMs,
- timing: agentResponse.timing || {},
- headers: agentResponse.headers || {},
- bodySizeBytes: agentResponse.bodySizeBytes || 0,
- validationErrors: agentResponse.validationErrors || [],
- error: agentResponse.error,
- }
- : {
- status: agentResponse.status,
- responseTimeMs: agentResponse.responseTimeMs,
- validationErrors: [],
- error: agentResponse.error,
- };
-
- return { region: region.code, result };
- } catch (error) {
- this.logger.error(
- { err: error, monitorId: monitor.id, regionCode: region.code },
- "Failed to execute monitor check through agent"
- );
- throw error;
- }
- }
-
- private async storeMonitorEvent(
- monitor: any,
- result: HttpCheckResult | TcpCheckResult,
- regionCode: string = "local"
- ): Promise<void> {
- // Helper to ensure timing values are non-negative or undefined
- const sanitizeTiming = (value: number | undefined): number | undefined => {
- if (value === undefined || value === null) return undefined;
- return value >= 0 ? Math.round(value) : undefined;
- };
-
- const event: MonitorEvent = {
- monitor_id: monitor.id,
- organization_id: monitor.organizationId,
- timestamp: DateTime.now().toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- monitor_type: monitor.monitorType,
- monitor_url: monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`,
- monitor_name: monitor.name,
- region: regionCode,
- status: result.status,
- status_code: (result as HttpCheckResult).statusCode,
- response_time_ms: Math.max(0, Math.round(result.responseTimeMs)),
- dns_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.dnsMs),
- tcp_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.tcpMs),
- tls_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.tlsMs),
- ttfb_ms: sanitizeTiming((result as HttpCheckResult).timing?.ttfbMs),
- transfer_time_ms: sanitizeTiming((result as HttpCheckResult).timing?.transferMs),
- validation_errors: result.validationErrors,
- response_headers: (result as HttpCheckResult).headers || {},
- response_size_bytes: (result as HttpCheckResult).bodySizeBytes,
- port: monitor.tcpConfig?.port,
- error_message: result.error?.message,
- error_type: result.error?.type,
- };
-
- try {
- await clickhouse.insert({
- table: "monitor_events",
- values: [event],
- format: "JSONEachRow",
- });
- } catch (error) {
- this.logger.error({ err: error, monitorId: monitor.id, regionCode }, "Failed to store monitor event");
- }
- }
-
- private async updateMonitorStatus(monitorId: number, result: HttpCheckResult | TcpCheckResult): Promise<void> {
- try {
- const now = new Date();
- const currentStatus = result.status === "success" ? "up" : "down";
-
- // Get current status to update consecutive counts
- const existingStatus = await db.query.uptimeMonitorStatus.findFirst({
- where: eq(uptimeMonitorStatus.monitorId, monitorId),
- });
-
- let consecutiveFailures = existingStatus?.consecutiveFailures || 0;
- let consecutiveSuccesses = existingStatus?.consecutiveSuccesses || 0;
- const previousStatus = existingStatus?.currentStatus;
-
- if (currentStatus === "up") {
- consecutiveSuccesses++;
- consecutiveFailures = 0;
- } else {
- consecutiveFailures++;
- consecutiveSuccesses = 0;
- }
-
- // Update or insert status
- if (existingStatus) {
- await db
- .update(uptimeMonitorStatus)
- .set({
- lastCheckedAt: now.toISOString(),
- currentStatus,
- consecutiveFailures,
- consecutiveSuccesses,
- updatedAt: now.toISOString(),
- })
- .where(eq(uptimeMonitorStatus.monitorId, monitorId));
- } else {
- await db.insert(uptimeMonitorStatus).values({
- monitorId,
- lastCheckedAt: now.toISOString(),
- currentStatus,
- consecutiveFailures,
- consecutiveSuccesses,
- updatedAt: now.toISOString(),
- });
- }
-
- // Handle incident creation/resolution based on consecutive failures/successes
- await this.handleIncidentManagement(
- monitorId,
- previousStatus || undefined,
- currentStatus,
- result,
- consecutiveFailures,
- consecutiveSuccesses
- );
- } catch (error) {
- this.logger.error({ err: error, monitorId }, "Failed to update monitor status");
- }
- }
-
- private async handleIncidentManagement(
- monitorId: number,
- previousStatus: string | undefined,
- currentStatus: string,
- result: HttpCheckResult | TcpCheckResult,
- consecutiveFailures: number,
- consecutiveSuccesses: number
- ): Promise<void> {
- try {
- // Get monitor details for incident creation
- const monitor = await db.query.uptimeMonitors.findFirst({
- where: eq(uptimeMonitors.id, monitorId),
- });
-
- if (!monitor) {
- this.logger.error({ monitorId }, "Monitor not found for incident management");
- return;
- }
-
- // Check for active incidents
- const activeIncident = await db.query.uptimeIncidents.findFirst({
- where: and(
- eq(uptimeIncidents.monitorId, monitorId),
- eq(uptimeIncidents.status, "active"),
- eq(uptimeIncidents.region, "local")
- ),
- });
-
- // Create incident when failures reach threshold
- if (currentStatus === "down" && consecutiveFailures === MonitorExecutor.FAILURE_THRESHOLD && !activeIncident) {
- const [newIncident] = await db
- .insert(uptimeIncidents)
- .values({
- organizationId: monitor.organizationId as string,
- monitorId: monitorId,
- region: "local",
- startTime: new Date().toISOString(),
- status: "active",
- lastError: result.error?.message || null,
- lastErrorType: result.error?.type || null,
- failureCount: 1,
- })
- .returning();
- this.logger.info({ incidentId: newIncident.id, monitorId }, "Created monitor incident");
-
- // Send notifications for new incident
- await this.notificationService.sendIncidentNotifications(monitor, newIncident, "down");
- }
- // Resolve incident when successes reach threshold after being down
- else if (currentStatus === "up" && consecutiveSuccesses === MonitorExecutor.SUCCESS_THRESHOLD && activeIncident) {
- const now = new Date().toISOString();
- await db
- .update(uptimeIncidents)
- .set({
- status: "resolved",
- endTime: now,
- resolvedAt: now,
- })
- .where(eq(uptimeIncidents.id, activeIncident.id));
- this.logger.info({ incidentId: activeIncident.id, monitorId }, "Resolved monitor incident");
-
- // Send recovery notifications
- await this.notificationService.sendIncidentNotifications(
- monitor,
- { ...activeIncident, status: "resolved", endTime: now },
- "recovery"
- );
- }
- // Status remains DOWN (Update failure count)
- else if (currentStatus === "down" && activeIncident) {
- await db
- .update(uptimeIncidents)
- .set({
- failureCount: (activeIncident.failureCount || 0) + 1,
- lastError: result.error?.message || activeIncident.lastError,
- lastErrorType: result.error?.type || activeIncident.lastErrorType,
- })
- .where(eq(uptimeIncidents.id, activeIncident.id));
- }
- } catch (error) {
- this.logger.error({ err: error, monitorId }, "Failed to manage monitor incident");
- }
- }
-
- private async handleRegionalIncident(
- monitor: any,
- region: string,
- result: HttpCheckResult | TcpCheckResult
- ): Promise<void> {
- try {
- const currentStatus = result.status === "success" ? "up" : "down";
-
- // Get recent events from ClickHouse to determine consecutive counts
- const recentEvents = await clickhouse.query({
- query: `
- SELECT status, timestamp
- FROM monitor_events
- WHERE monitor_id = {monitorId:Int32}
- AND region = {region:String}
- ORDER BY timestamp DESC
- LIMIT {limit:Int32}
- `,
- query_params: {
- monitorId: monitor.id,
- region: region,
- limit: MonitorExecutor.FAILURE_THRESHOLD + 1, // Get enough events to check threshold
- },
- });
-
- const events = await recentEvents.json<{ status: string; timestamp: string }>();
-
- // Count consecutive failures/successes from most recent events
- let consecutiveFailures = 0;
- let consecutiveSuccesses = 0;
-
- // Start with current result
- if (currentStatus === "down") {
- consecutiveFailures = 1;
- } else {
- consecutiveSuccesses = 1;
- }
-
- // Check previous events
- for (const event of events.data) {
- if (currentStatus === "down" && event.status === "failure") {
- consecutiveFailures++;
- } else if (currentStatus === "up" && event.status === "success") {
- consecutiveSuccesses++;
- } else {
- break; // Different status, not consecutive
- }
- }
-
- // Check for active incidents in this region
- const activeIncident = await db.query.uptimeIncidents.findFirst({
- where: and(
- eq(uptimeIncidents.monitorId, monitor.id),
- eq(uptimeIncidents.status, "active"),
- eq(uptimeIncidents.region, region)
- ),
- });
-
- // Create incident when failures reach threshold
- if (currentStatus === "down" && consecutiveFailures === MonitorExecutor.FAILURE_THRESHOLD && !activeIncident) {
- const [newIncident] = await db
- .insert(uptimeIncidents)
- .values({
- organizationId: monitor.organizationId as string,
- monitorId: monitor.id,
- region: region,
- startTime: new Date().toISOString(),
- status: "active",
- lastError: result.error?.message || null,
- lastErrorType: result.error?.type || null,
- failureCount: 1,
- })
- .returning();
- this.logger.info(
- { incidentId: newIncident.id, monitorId: monitor.id, regionCode: region },
- "Created regional monitor incident"
- );
-
- // Send notifications for new regional incident
- await this.notificationService.sendIncidentNotifications(monitor, newIncident, "down");
- }
- // Resolve incident when successes reach threshold
- else if (currentStatus === "up" && consecutiveSuccesses === MonitorExecutor.SUCCESS_THRESHOLD && activeIncident) {
- const now = new Date().toISOString();
- await db
- .update(uptimeIncidents)
- .set({
- status: "resolved",
- endTime: now,
- resolvedAt: now,
- updatedAt: now,
- })
- .where(eq(uptimeIncidents.id, activeIncident.id));
- this.logger.info(
- { incidentId: activeIncident.id, monitorId: monitor.id, regionCode: region },
- "Resolved regional monitor incident"
- );
-
- // Send recovery notifications for regional incident
- await this.notificationService.sendIncidentNotifications(
- monitor,
- { ...activeIncident, status: "resolved", endTime: now },
- "recovery"
- );
- }
- // If check failed and there's already an active incident, update it
- else if (currentStatus === "down" && activeIncident) {
- await db
- .update(uptimeIncidents)
- .set({
- failureCount: (activeIncident.failureCount || 0) + 1,
- lastError: result.error?.message || activeIncident.lastError,
- lastErrorType: result.error?.type || activeIncident.lastErrorType,
- })
- .where(eq(uptimeIncidents.id, activeIncident.id));
- }
- } catch (error) {
- this.logger.error(
- { err: error, monitorId: monitor.id, regionCode: region },
- "Failed to manage regional monitor incident"
- );
- }
- }
-
- async shutdown(): Promise<void> {
- this.logger.info("Shutting down BullMQ monitor executor...");
- this.isShuttingDown = true;
-
- if (this.worker) {
- try {
- // Close the worker with a timeout
- await Promise.race([
- this.worker.close(),
- new Promise((_, reject) => setTimeout(() => reject(new Error("Worker close timeout")), 5000)),
- ]);
- this.logger.info("BullMQ monitor executor shut down successfully");
- } catch (error) {
- this.logger.error({ err: error }, "Error closing monitor worker");
- // Force close if needed
- this.worker = null;
- }
- }
- }
-}
diff --git a/server/src/services/uptime/monitorScheduler.ts b/server/src/services/uptime/monitorScheduler.ts
deleted file mode 100644
index 6cf9aa2b3..000000000
--- a/server/src/services/uptime/monitorScheduler.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { Queue, QueueEvents } from "bullmq";
-import { eq } from "drizzle-orm";
-import { db } from "../../db/postgres/postgres.js";
-import { uptimeMonitors } from "../../db/postgres/schema.js";
-import { createServiceLogger } from "../../lib/logger/logger.js";
-import { MonitorCheckJob } from "./types.js";
-
-export class MonitorScheduler {
- private queue: Queue;
- private queueEvents: QueueEvents;
- private isShuttingDown = false;
- private connection: { host: string; port: number; password?: string };
- private logger = createServiceLogger("monitor-scheduler");
-
- constructor() {
- // Get Redis connection from environment
- this.connection = {
- host: process.env.REDIS_HOST || "localhost",
- port: parseInt(process.env.REDIS_PORT || "6379", 10),
- ...(process.env.REDIS_PASSWORD && { password: process.env.REDIS_PASSWORD }),
- };
-
- this.logger.info({ host: this.connection.host, port: this.connection.port }, "BullMQ connecting to Redis");
-
- this.queue = new Queue("monitor-checks", {
- connection: this.connection,
- defaultJobOptions: {
- removeOnComplete: {
- count: 100, // Keep last 100 completed jobs
- age: 3600, // Keep for 1 hour
- },
- removeOnFail: {
- count: 100, // Keep last 100 failed jobs
- age: 86400, // Keep for 24 hours
- },
- },
- });
-
- this.queueEvents = new QueueEvents("monitor-checks", {
- connection: this.connection,
- });
- }
-
- async initialize(): Promise<void> {
- this.logger.info("Initializing BullMQ monitor scheduler...");
-
- // Wait for queue to be ready
- await this.queue.waitUntilReady();
- await this.queueEvents.waitUntilReady();
-
- this.logger.info("BullMQ queue ready");
-
- // Clear any stale jobs from previous runs
- await this.clearStaleJobs();
-
- // Load and schedule all active monitors
- await this.loadAndScheduleMonitors();
-
- this.logger.info("BullMQ monitor scheduler initialized");
- }
-
- private async clearStaleJobs(): Promise<void> {
- try {
- // For Dragonfly compatibility, we'll clear jobs more carefully
- // First, try to get counts to see if there are any jobs
- const counts = await this.queue.getJobCounts();
- this.logger.debug({ counts }, "Current job counts");
-
- // Only try to clear if there are actually jobs
- if (counts.delayed > 0 || counts.waiting > 0 || counts.active > 0) {
- try {
- // Try to clean specific job types one by one
- const waitingJobs = await this.queue.getJobs(["waiting"]);
- const activeJobs = await this.queue.getJobs(["active"]);
-
- this.logger.debug({ waitingJobs: waitingJobs.length, activeJobs: activeJobs.length }, "Found stale jobs");
-
- // Remove jobs individually
- for (const job of [...waitingJobs, ...activeJobs]) {
- try {
- await job.remove();
- } catch (err) {
- this.logger.warn({ jobId: job.id, err }, "Failed to remove job");
- }
- }
-
- this.logger.info("Cleared stale jobs");
- } catch (err) {
- this.logger.warn({ err }, "Could not clear all job types");
- }
- } else {
- this.logger.debug("No stale jobs to clear");
- }
- } catch (error) {
- this.logger.error({ err: error }, "Error clearing stale jobs");
- // Continue anyway - this is not critical for startup
- }
- }
-
- private async loadAndScheduleMonitors(): Promise<void> {
- try {
- // Load all enabled monitors
- const monitors = await db.select().from(uptimeMonitors).where(eq(uptimeMonitors.enabled, true));
-
- this.logger.info({ monitorCount: monitors.length }, "Found enabled monitors");
-
- // Schedule each monitor
- for (const monitor of monitors) {
- await this.scheduleMonitor(monitor.id, monitor.intervalSeconds);
- }
- } catch (error) {
- this.logger.error({ err: error }, "Error loading monitors");
- }
- }
-
- async scheduleMonitor(monitorId: number, intervalSeconds: number): Promise<void> {
- if (this.isShuttingDown) return;
-
- try {
- // Remove existing jobs for this monitor
- await this.removeMonitorSchedule(monitorId);
-
- const jobName = `monitor-${monitorId}`;
- const jobData: MonitorCheckJob = {
- monitorId,
- intervalSeconds,
- };
-
- // Add recurring job using repeat option
- const job = await this.queue.add(jobName, jobData, {
- repeat: {
- every: intervalSeconds * 1000, // Convert to milliseconds
- },
- jobId: jobName, // Use monitor ID as job ID to prevent duplicates
- });
-
- this.logger.info({ monitorId, intervalSeconds, jobId: job.id }, "Scheduled monitor");
- } catch (error) {
- this.logger.error({ monitorId, err: error }, "Error scheduling monitor");
- }
- }
-
- async removeMonitorSchedule(monitorId: number): Promise<void> {
- try {
- const jobName = `monitor-${monitorId}`;
-
- // First, remove repeatable job configuration
- const repeatableJobs = await this.queue.getRepeatableJobs();
- const monitorRepeatableJobs = repeatableJobs.filter(job => job.name === jobName || job.id === jobName);
-
- await Promise.all(monitorRepeatableJobs.map(job => this.queue.removeRepeatableByKey(job.key)));
-
- // Then remove any non-repeat jobs (only remove jobs that don't belong to scheduler)
- const jobs = await this.queue.getJobs(["waiting", "active", "completed", "failed"]);
- const monitorJobs = jobs.filter(job => {
- // Only remove jobs that match our monitor and aren't repeat jobs
- return (job.name === jobName || job.id === jobName) && !job.repeatJobKey;
- });
-
- await Promise.all(
- monitorJobs.map(async job => {
- try {
- await job.remove();
- } catch (err) {
- // Ignore errors for jobs that can't be removed (e.g., repeat jobs)
- this.logger.warn({ jobId: job.id, err }, "Could not remove job");
- }
- })
- );
-
- this.logger.info({ monitorId }, "Removed schedule for monitor");
- } catch (error) {
- this.logger.error({ monitorId, err: error }, "Error removing monitor schedule");
- }
- }
-
- async updateMonitorSchedule(monitorId: number, intervalSeconds: number): Promise<void> {
- await this.scheduleMonitor(monitorId, intervalSeconds);
- }
-
- async triggerImmediateCheck(monitorId: number): Promise<void> {
- try {
- const jobName = `monitor-${monitorId}-immediate`;
- const jobData: MonitorCheckJob = {
- monitorId,
- intervalSeconds: 0, // Not used for immediate checks
- };
-
- // Add a one-time job for immediate execution
- const job = await this.queue.add(jobName, jobData, {
- delay: 0, // No delay
- priority: 1, // Higher priority than regular checks
- removeOnComplete: true,
- removeOnFail: false,
- });
-
- this.logger.info({ monitorId, jobId: job.id }, "Triggered immediate check for monitor");
- } catch (error) {
- this.logger.error({ monitorId, err: error }, "Error triggering immediate check for monitor");
- }
- }
-
- async shutdown(): Promise<void> {
- this.logger.info("Shutting down BullMQ monitor scheduler...");
- this.isShuttingDown = true;
-
- try {
- // Close queue events and queue with timeouts
- await Promise.all([
- Promise.race([
- this.queueEvents.close(),
- new Promise((_, reject) => setTimeout(() => reject(new Error("Queue events close timeout")), 3000)),
- ]).catch(err => this.logger.error({ err }, "Queue events close error")),
- Promise.race([
- this.queue.close(),
- new Promise((_, reject) => setTimeout(() => reject(new Error("Queue close timeout")), 3000)),
- ]).catch(err => this.logger.error({ err }, "Queue close error")),
- ]);
-
- this.logger.info("BullMQ monitor scheduler shut down successfully");
- } catch (error) {
- this.logger.error({ err: error }, "Error during scheduler shutdown");
- }
- }
-
- getQueue(): Queue {
- return this.queue;
- }
-}
diff --git a/server/src/services/uptime/notificationService.ts b/server/src/services/uptime/notificationService.ts
deleted file mode 100644
index 4061defbe..000000000
--- a/server/src/services/uptime/notificationService.ts
+++ /dev/null
@@ -1,411 +0,0 @@
-import { DateTime } from "luxon";
-import { and, eq, InferSelectModel } from "drizzle-orm";
-import { db } from "../../db/postgres/postgres.js";
-import { notificationChannels } from "../../db/postgres/schema.js";
-import { createServiceLogger } from "../../lib/logger/logger.js";
-import { sendEmail } from "../../lib/email/email.js";
-import { sendSMS } from "../../lib/twilio.js";
-
-// Type inferred from Drizzle schema
-type NotificationChannel = InferSelectModel<typeof notificationChannels>;
-
-interface Monitor {
- id: number;
- organizationId: string;
- name?: string | null;
- monitorType: string;
- httpConfig?: {
- url: string;
- } | null;
- tcpConfig?: {
- host: string;
- port: number;
- } | null;
-}
-
-interface Incident {
- id: number;
- region?: string | null;
- startTime: string;
- endTime?: string | null;
- lastError?: string | null;
- lastErrorType?: string | null;
- status: string;
-}
-
-export class NotificationService {
- private logger = createServiceLogger("notification-service");
-
- async sendTestNotification(
- channel: NotificationChannel,
- monitor: Monitor,
- incident: Incident,
- eventType: "down" | "recovery"
- ): Promise<void> {
- try {
- if (channel.type === "email" && channel.config.email) {
- await this.sendEmailNotification(channel.config.email, monitor, incident, eventType);
- } else if (channel.type === "discord" && channel.config.webhookUrl) {
- await this.sendDiscordNotification(channel.config.webhookUrl, monitor, incident, eventType);
- } else if (channel.type === "slack" && channel.config.slackWebhookUrl) {
- await this.sendSlackNotification(
- channel.config.slackWebhookUrl,
- channel.config.slackChannel,
- monitor,
- incident,
- eventType
- );
- } else if (channel.type === "sms" && channel.config.phoneNumber) {
- await this.sendSMSNotification(channel.config.phoneNumber, monitor, incident, eventType);
- }
- } catch (error) {
- this.logger.error({ channelType: channel.type, err: error }, "Failed to send test notification");
- throw error;
- }
- }
-
- async sendIncidentNotifications(monitor: Monitor, incident: Incident, eventType: "down" | "recovery"): Promise<void> {
- try {
- // Get all enabled notification channels for this organization
- const channels = await db.query.notificationChannels.findMany({
- where: and(
- eq(notificationChannels.organizationId, monitor.organizationId),
- eq(notificationChannels.enabled, true)
- ),
- });
-
- // Filter channels that should receive notifications for this monitor
- const relevantChannels = channels.filter(channel => {
- // Check if channel triggers for this event type
- if (!channel.triggerEvents?.includes(eventType)) {
- return false;
- }
-
- // Check if channel monitors this specific monitor or all monitors
- if (channel.monitorIds === null) {
- // null means all monitors
- return true;
- }
-
- return channel.monitorIds.includes(monitor.id);
- });
-
- // Check cooldown for each channel
- const now = new Date();
- const channelsToNotify = relevantChannels.filter(channel => {
- if (!channel.lastNotifiedAt) return true;
-
- const lastNotified = new Date(channel.lastNotifiedAt);
- const cooldownMs = (channel.cooldownMinutes || 5) * 60 * 1000;
- return now.getTime() - lastNotified.getTime() > cooldownMs;
- });
-
- // Send notifications for each channel
- for (const channel of channelsToNotify) {
- try {
- if (channel.type === "email" && channel.config.email) {
- await this.sendEmailNotification(channel.config.email, monitor, incident, eventType);
- } else if (channel.type === "discord" && channel.config.webhookUrl) {
- await this.sendDiscordNotification(channel.config.webhookUrl, monitor, incident, eventType);
- } else if (channel.type === "slack" && channel.config.slackWebhookUrl) {
- await this.sendSlackNotification(
- channel.config.slackWebhookUrl,
- channel.config.slackChannel,
- monitor,
- incident,
- eventType
- );
- } else if (channel.type === "sms" && channel.config.phoneNumber) {
- await this.sendSMSNotification(channel.config.phoneNumber, monitor, incident, eventType);
- }
-
- // Update last notified time for successful notifications
- await db
- .update(notificationChannels)
- .set({ lastNotifiedAt: now.toISOString() })
- .where(eq(notificationChannels.id, channel.id));
- } catch (error) {
- this.logger.error(
- { channelType: channel.type, channelId: channel.id, err: error },
- "Failed to send notification"
- );
- }
- }
- } catch (error) {
- this.logger.error({ err: error }, "Failed to send incident notifications");
- }
- }
-
- private async sendEmailNotification(
- email: string,
- monitor: Monitor,
- incident: Incident,
- eventType: "down" | "recovery"
- ): Promise<void> {
- const monitorName =
- monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
- const region = incident.region || "local";
- const incidentTime = DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL);
-
- let subject: string;
- let html: string;
-
- if (eventType === "down") {
- subject = `πŸ”΄ Monitor Alert: ${monitorName} is DOWN`;
- html = `
- <h2>Monitor Alert: ${monitorName} is DOWN</h2>
- <p>Your monitor has stopped responding.</p>
- <ul>
- <li><strong>Monitor:</strong> ${monitorName}</li>
- <li><strong>Type:</strong> ${monitor.monitorType.toUpperCase()}</li>
- <li><strong>Region:</strong> ${region}</li>
- <li><strong>Time:</strong> ${incidentTime}</li>
- ${incident.lastError ? `<li><strong>Error:</strong> ${incident.lastError}</li>` : ""}
- </ul>
- <p>We'll continue monitoring and notify you when the service recovers.</p>
- `;
- } else {
- const duration = incident.endTime
- ? DateTime.fromSQL(incident.endTime)
- .diff(DateTime.fromSQL(incident.startTime))
- .toFormat("hh 'hours' mm 'minutes'")
- : "Unknown";
-
- subject = `βœ… Monitor Recovery: ${monitorName} is UP`;
- html = `
- <h2>Monitor Recovery: ${monitorName} is UP</h2>
- <p>Your monitor has recovered and is responding normally.</p>
- <ul>
- <li><strong>Monitor:</strong> ${monitorName}</li>
- <li><strong>Type:</strong> ${monitor.monitorType.toUpperCase()}</li>
- <li><strong>Region:</strong> ${region}</li>
- <li><strong>Downtime Duration:</strong> ${duration}</li>
- <li><strong>Recovery Time:</strong> ${DateTime.now().toLocaleString(DateTime.DATETIME_FULL)}</li>
- </ul>
- `;
- }
-
- await sendEmail(email, subject, html);
- this.logger.info({ eventType, monitorId: monitor.id }, "Sent email notification");
- }
-
- private async sendDiscordNotification(
- webhookUrl: string,
- monitor: Monitor,
- incident: Incident,
- eventType: "down" | "recovery"
- ): Promise<void> {
- const monitorName =
- monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
- const region = incident.region || "local";
-
- const embed = {
- title:
- eventType === "down" ? `πŸ”΄ Monitor Alert: ${monitorName} is DOWN` : `βœ… Monitor Recovery: ${monitorName} is UP`,
- color: eventType === "down" ? 0xff0000 : 0x00ff00,
- fields: [
- {
- name: "Monitor",
- value: monitorName,
- inline: true,
- },
- {
- name: "Type",
- value: monitor.monitorType.toUpperCase(),
- inline: true,
- },
- {
- name: "Region",
- value: region,
- inline: true,
- },
- ...(eventType === "down"
- ? [
- {
- name: "Time",
- value: DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL),
- inline: false,
- },
- ...(incident.lastError
- ? [
- {
- name: "Error",
- value: incident.lastError,
- inline: false,
- },
- ]
- : []),
- ]
- : [
- {
- name: "Downtime Duration",
- value: incident.endTime
- ? DateTime.fromSQL(incident.endTime)
- .diff(DateTime.fromSQL(incident.startTime))
- .toFormat("hh 'hours' mm 'minutes'")
- : "Unknown",
- inline: true,
- },
- {
- name: "Recovery Time",
- value: DateTime.now().toLocaleString(DateTime.DATETIME_FULL),
- inline: true,
- },
- ]),
- ],
- timestamp: new Date().toISOString(),
- };
-
- const response = await fetch(webhookUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- embeds: [embed],
- }),
- });
-
- if (!response.ok) {
- throw new Error(`Discord webhook failed: ${response.status} ${response.statusText}`);
- }
-
- this.logger.info({ eventType, monitorId: monitor.id }, "Sent Discord notification");
- }
-
- private async sendSlackNotification(
- webhookUrl: string,
- slackChannel: string | undefined,
- monitor: Monitor,
- incident: Incident,
- eventType: "down" | "recovery"
- ): Promise<void> {
- const monitorName =
- monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
- const region = incident.region || "local";
- const emoji = eventType === "down" ? ":red_circle:" : ":white_check_mark:";
-
- const blocks: any[] = [
- {
- type: "header",
- text: {
- type: "plain_text",
- text:
- eventType === "down"
- ? `${emoji} Monitor Alert: ${monitorName} is DOWN`
- : `${emoji} Monitor Recovery: ${monitorName} is UP`,
- emoji: true,
- },
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*Monitor:*\n${monitorName}`,
- },
- {
- type: "mrkdwn",
- text: `*Type:*\n${monitor.monitorType.toUpperCase()}`,
- },
- {
- type: "mrkdwn",
- text: `*Region:*\n${region}`,
- },
- ...(eventType === "down"
- ? [
- {
- type: "mrkdwn",
- text: `*Time:*\n${DateTime.fromSQL(incident.startTime).toLocaleString(DateTime.DATETIME_FULL)}`,
- },
- ]
- : [
- {
- type: "mrkdwn",
- text: `*Duration:*\n${
- incident.endTime
- ? DateTime.fromSQL(incident.endTime)
- .diff(DateTime.fromSQL(incident.startTime))
- .toFormat("hh 'hours' mm 'minutes'")
- : "Unknown"
- }`,
- },
- ]),
- ],
- },
- ];
-
- if (eventType === "down" && incident.lastError) {
- blocks.push({
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*Error:* ${incident.lastError}`,
- },
- });
- }
-
- const payload: any = {
- blocks,
- text: eventType === "down" ? `Monitor Alert: ${monitorName} is DOWN` : `Monitor Recovery: ${monitorName} is UP`,
- };
-
- if (slackChannel) {
- payload.channel = slackChannel;
- }
-
- const response = await fetch(webhookUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(payload),
- });
-
- if (!response.ok) {
- throw new Error(`Slack webhook failed: ${response.status} ${response.statusText}`);
- }
-
- this.logger.info({ eventType, monitorId: monitor.id }, "Sent Slack notification");
- }
-
- private async sendSMSNotification(
- phoneNumber: string,
- monitor: Monitor,
- incident: Incident,
- eventType: "down" | "recovery"
- ): Promise<void> {
- const monitorName =
- monitor.name || monitor.httpConfig?.url || `${monitor.tcpConfig?.host}:${monitor.tcpConfig?.port}`;
- const region = incident.region || "local";
-
- let message: string;
- if (eventType === "down") {
- message = `πŸ”΄ ALERT: ${monitorName} is DOWN in ${region}`;
- if (incident.lastError) {
- // Truncate error to fit SMS limits
- const truncatedError =
- incident.lastError.length > 50 ? incident.lastError.substring(0, 47) + "..." : incident.lastError;
- message += ` - ${truncatedError}`;
- }
- } else {
- const duration = incident.endTime
- ? DateTime.fromSQL(incident.endTime).diff(DateTime.fromSQL(incident.startTime)).toFormat("h'h' m'm'")
- : "Unknown";
- message = `βœ… RECOVERY: ${monitorName} is UP in ${region} after ${duration} downtime`;
- }
-
- // SMS messages should be concise - limit to 160 chars for single SMS
- if (message.length > 160) {
- message = message.substring(0, 157) + "...";
- }
-
- const result = await sendSMS(phoneNumber, message);
-
- if (!result.success) {
- throw new Error(result.error || "Failed to send SMS");
- }
-
- this.logger.info({ eventType, monitorId: monitor.id }, "Sent SMS notification");
- }
-}
diff --git a/server/src/services/uptime/regionHealthChecker.ts b/server/src/services/uptime/regionHealthChecker.ts
deleted file mode 100644
index 17b5055f8..000000000
--- a/server/src/services/uptime/regionHealthChecker.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { eq } from "drizzle-orm";
-import { db } from "../../db/postgres/postgres.js";
-import { agentRegions } from "../../db/postgres/schema.js";
-import { createServiceLogger } from "../../lib/logger/logger.js";
-
-export class RegionHealthChecker {
- private intervalMs: number;
- private intervalId: NodeJS.Timeout | null = null;
- private logger = createServiceLogger("region-health-checker");
-
- constructor(intervalMs: number = 60000) {
- // Default: 1 minute
- this.intervalMs = intervalMs;
- }
-
- async start(): Promise<void> {
- this.logger.info({ intervalMs: this.intervalMs }, "Starting region health checker");
-
- // Run initial check
- await this.checkAllRegions();
-
- // Schedule periodic checks
- this.intervalId = setInterval(async () => {
- await this.checkAllRegions();
- }, this.intervalMs);
- }
-
- async stop(): Promise<void> {
- if (this.intervalId) {
- clearInterval(this.intervalId);
- this.intervalId = null;
- this.logger.info("Region health checker stopped");
- }
- }
-
- private async checkAllRegions(): Promise<void> {
- try {
- const regions = await db.query.agentRegions.findMany({
- where: eq(agentRegions.enabled, true),
- });
-
- // Filter out local region
- const remoteRegions = regions.filter(r => r.code !== "local");
-
- this.logger.debug({ regionCount: remoteRegions.length }, "Checking remote region health");
-
- const healthPromises = remoteRegions.map(region =>
- this.checkRegionHealth(region).catch(error => {
- this.logger.error({ err: error, regionCode: region.code }, "Error checking region health");
- return { region, isHealthy: false };
- })
- );
-
- const results = await Promise.all(healthPromises);
-
- // Update health status in database
- for (const { region, isHealthy } of results) {
- await db
- .update(agentRegions)
- .set({
- isHealthy,
- lastHealthCheck: new Date().toISOString(),
- })
- .where(eq(agentRegions.code, region.code));
- }
-
- const healthyCount = results.filter(r => r.isHealthy).length;
- this.logger.info({ healthyCount, totalRegions: remoteRegions.length }, "Region health check complete");
- } catch (error) {
- this.logger.error({ err: error }, "Error in region health check");
- }
- }
-
- private async checkRegionHealth(region: any): Promise<{ region: any; isHealthy: boolean }> {
- try {
- const response = await fetch(`${region.endpointUrl}/health`, {
- method: "GET",
- signal: AbortSignal.timeout(10000), // 10 second timeout
- });
-
- if (!response.ok) {
- this.logger.warn({ regionCode: region.code, status: response.status }, "Region returned non-ok status");
- return { region, isHealthy: false };
- }
-
- const data = await response.json();
-
- // Verify the response contains expected fields
- if (data.status === "ok" && data.region === region.code) {
- return { region, isHealthy: true };
- }
-
- this.logger.warn({ regionCode: region.code, response: data }, "Region returned unexpected response");
- return { region, isHealthy: false };
- } catch (error) {
- this.logger.error({ regionCode: region.code, err: error }, "Health check failed for region");
- return { region, isHealthy: false };
- }
- }
-}
diff --git a/server/src/services/uptime/types.ts b/server/src/services/uptime/types.ts
deleted file mode 100644
index f5276fc18..000000000
--- a/server/src/services/uptime/types.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-export interface MonitorCheckJob {
- monitorId: number;
- intervalSeconds: number;
-}
-
-export interface HttpCheckResult {
- status: "success" | "failure" | "timeout";
- statusCode?: number;
- responseTimeMs: number;
- timing: {
- dnsMs?: number;
- tcpMs?: number;
- tlsMs?: number;
- ttfbMs?: number;
- transferMs?: number;
- };
- headers: Record<string, string>;
- bodySizeBytes: number;
- validationErrors: string[];
- error?: {
- message: string;
- type: string;
- };
-}
-
-export interface TcpCheckResult {
- status: "success" | "failure" | "timeout";
- responseTimeMs: number;
- validationErrors: string[];
- error?: {
- message: string;
- type: string;
- };
-}
-
-export type CheckResult = HttpCheckResult | TcpCheckResult;
-
-export interface ValidationRule {
- type:
- | "status_code"
- | "response_time"
- | "response_body_contains"
- | "response_body_not_contains"
- | "header_exists"
- | "header_value"
- | "response_size";
- operator?: "equals" | "not_equals" | "in" | "not_in" | "less_than" | "greater_than" | "contains";
- value?: number | number[] | string;
- header?: string;
- caseSensitive?: boolean;
-}
-
-export interface MonitorEvent {
- monitor_id: number;
- organization_id: string;
- timestamp: string; // ClickHouse DateTime format: YYYY-MM-DD HH:MM:SS
- monitor_type: string;
- monitor_url: string;
- monitor_name: string;
- region: string;
- status: string;
- status_code?: number;
- response_time_ms: number;
- dns_time_ms?: number;
- tcp_time_ms?: number;
- tls_time_ms?: number;
- ttfb_ms?: number;
- transfer_time_ms?: number;
- validation_errors: string[];
- response_headers: Record<string, string>;
- response_size_bytes?: number;
- port?: number;
- error_message?: string;
- error_type?: string;
-}
diff --git a/server/src/services/uptime/uptimeService.ts b/server/src/services/uptime/uptimeService.ts
deleted file mode 100644
index d94397505..000000000
--- a/server/src/services/uptime/uptimeService.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { MonitorScheduler } from "./monitorScheduler.js";
-import { MonitorExecutor } from "./monitorExecutor.js";
-import { RegionHealthChecker } from "./regionHealthChecker.js";
-import { createServiceLogger } from "../../lib/logger/logger.js";
-
-class UptimeService {
- private scheduler: MonitorScheduler;
- private executor: MonitorExecutor;
- private regionHealthChecker: RegionHealthChecker;
- private initialized = false;
- private initializationPromise: Promise<void> | null = null;
- private logger = createServiceLogger("uptime");
-
- constructor() {
- this.scheduler = new MonitorScheduler();
- this.executor = new MonitorExecutor(10); // 10 concurrent workers
- this.regionHealthChecker = new RegionHealthChecker(60000); // Check every minute
- }
-
- async initialize(): Promise<void> {
- if (this.initialized) {
- this.logger.debug("Uptime service already initialized");
- return;
- }
-
- // If already initializing, return the existing promise
- if (this.initializationPromise) {
- return this.initializationPromise;
- }
-
- // Create and store the initialization promise
- this.initializationPromise = this.performInitialization();
- return this.initializationPromise;
- }
-
- private async performInitialization(): Promise<void> {
- try {
- this.logger.info("Initializing BullMQ uptime monitoring service...");
-
- // Initialize scheduler (creates queue, loads and schedules all monitors)
- await this.scheduler.initialize();
-
- // Start executor (begins processing jobs)
- await this.executor.start();
-
- // Start region health checker
- await this.regionHealthChecker.start();
-
- this.initialized = true;
- this.logger.info("BullMQ uptime monitoring service initialized successfully");
- } catch (error) {
- this.logger.error({ err: error }, "Failed to initialize uptime service");
- this.initializationPromise = null; // Reset on failure
- throw error;
- }
- }
-
- async shutdown(): Promise<void> {
- this.logger.info("Shutting down BullMQ uptime monitoring service...");
-
- try {
- // Stop region health checker
- await this.regionHealthChecker.stop();
-
- // Shutdown executor first (stops processing new jobs)
- await this.executor.shutdown();
-
- // Then shutdown scheduler (closes queue)
- await this.scheduler.shutdown();
-
- this.initialized = false;
- this.logger.info("BullMQ uptime monitoring service shut down successfully");
- } catch (error) {
- this.logger.error({ err: error }, "Error during uptime service shutdown");
- }
- }
-
- // Methods for managing monitors after CRUD operations
- async onMonitorCreated(monitorId: number, intervalSeconds: number): Promise<void> {
- // Wait for initialization if it's in progress
- if (!this.initialized && this.initializationPromise) {
- await this.initializationPromise;
- }
-
- if (!this.initialized) {
- this.logger.warn("Uptime service not initialized, cannot schedule monitor");
- return;
- }
-
- // Schedule the monitor for recurring checks
- await this.scheduler.scheduleMonitor(monitorId, intervalSeconds);
-
- // Trigger an immediate check
- await this.scheduler.triggerImmediateCheck(monitorId);
- }
-
- async onMonitorUpdated(monitorId: number, intervalSeconds: number, enabled: boolean): Promise<void> {
- // Wait for initialization if it's in progress
- if (!this.initialized && this.initializationPromise) {
- await this.initializationPromise;
- }
-
- if (!this.initialized) {
- this.logger.warn("Uptime service not initialized, cannot update monitor");
- return;
- }
-
- if (enabled) {
- await this.scheduler.updateMonitorSchedule(monitorId, intervalSeconds);
- // Trigger immediate check when monitor is re-enabled
- await this.scheduler.triggerImmediateCheck(monitorId);
- } else {
- await this.scheduler.removeMonitorSchedule(monitorId);
- }
- }
-
- async onMonitorDeleted(monitorId: number): Promise<void> {
- // Wait for initialization if it's in progress
- if (!this.initialized && this.initializationPromise) {
- await this.initializationPromise;
- }
-
- if (!this.initialized) {
- this.logger.warn("Uptime service not initialized, cannot delete monitor");
- return;
- }
-
- await this.scheduler.removeMonitorSchedule(monitorId);
- }
-}
-
-// Export singleton instance
-export const uptimeService = new UptimeService();
diff --git a/server/src/services/uptime/validationEngine.test.ts b/server/src/services/uptime/validationEngine.test.ts
deleted file mode 100644
index 131d7e1cc..000000000
--- a/server/src/services/uptime/validationEngine.test.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { applyValidationRules } from "./validationEngine.js";
-import { HttpCheckResult, ValidationRule } from "./types.js";
-
-function createResult(overrides: Partial<HttpCheckResult> = {}): HttpCheckResult {
- return {
- status: "success",
- statusCode: 200,
- responseTimeMs: 150,
- timing: {},
- headers: {},
- bodySizeBytes: 1024,
- validationErrors: [],
- ...overrides,
- };
-}
-
-describe("applyValidationRules", () => {
- it("returns no errors for an empty rule list", () => {
- expect(applyValidationRules(createResult(), [])).toEqual([]);
- });
-
- describe("status_code", () => {
- it("passes and fails 'equals'", () => {
- const rule: ValidationRule = { type: "status_code", operator: "equals", value: 200 };
- expect(applyValidationRules(createResult({ statusCode: 200 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ statusCode: 500 }), [rule])).toEqual([
- "Status code 500 does not equal 200",
- ]);
- });
-
- it("passes and fails 'not_equals'", () => {
- const rule: ValidationRule = { type: "status_code", operator: "not_equals", value: 500 };
- expect(applyValidationRules(createResult({ statusCode: 200 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ statusCode: 500 }), [rule])).toEqual(["Status code 500 equals 500"]);
- });
-
- it("passes and fails 'in' with an array value", () => {
- const rule: ValidationRule = { type: "status_code", operator: "in", value: [200, 201, 204] };
- expect(applyValidationRules(createResult({ statusCode: 204 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ statusCode: 404 }), [rule])).toEqual([
- "Status code 404 is not in [200, 201, 204]",
- ]);
- });
-
- it("passes and fails 'not_in' with an array value", () => {
- const rule: ValidationRule = { type: "status_code", operator: "not_in", value: [500, 502, 503] };
- expect(applyValidationRules(createResult({ statusCode: 200 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ statusCode: 502 }), [rule])).toEqual([
- "Status code 502 is in [500, 502, 503]",
- ]);
- });
-
- it("fails explicitly when the status code is falsy", () => {
- // Fail-closed: a missing status code (connection-level failure) or a literal 0
- // means no response was received, so a status_code rule must fail explicitly
- // rather than silently pass.
- const rule: ValidationRule = { type: "status_code", operator: "equals", value: 200 };
- expect(applyValidationRules(createResult({ statusCode: undefined }), [rule])).toEqual([
- "No status code available to validate",
- ]);
- expect(applyValidationRules(createResult({ statusCode: 0 }), [rule])).toEqual([
- "No status code available to validate",
- ]);
- });
-
- it("fails 'in' and 'not_in' when the value is not an array", () => {
- // Fail-closed: a scalar operand on in/not_in is a misconfigured rule and must
- // surface as a validation failure instead of silently passing.
- expect(
- applyValidationRules(createResult({ statusCode: 404 }), [{ type: "status_code", operator: "in", value: 200 }])
- ).toEqual(['Validation rule misconfigured: "in" operator requires an array value']);
- expect(
- applyValidationRules(createResult({ statusCode: 500 }), [
- { type: "status_code", operator: "not_in", value: 500 },
- ])
- ).toEqual(['Validation rule misconfigured: "not_in" operator requires an array value']);
- });
- });
-
- describe("response_time", () => {
- it("'less_than' fails exactly at the threshold and passes just below", () => {
- const rule: ValidationRule = { type: "response_time", operator: "less_than", value: 500 };
- expect(applyValidationRules(createResult({ responseTimeMs: 499 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ responseTimeMs: 500 }), [rule])).toEqual([
- "Response time 500ms is not less than 500ms",
- ]);
- expect(applyValidationRules(createResult({ responseTimeMs: 501 }), [rule])).toEqual([
- "Response time 501ms is not less than 500ms",
- ]);
- });
-
- it("'greater_than' fails exactly at the threshold and passes just above", () => {
- const rule: ValidationRule = { type: "response_time", operator: "greater_than", value: 100 };
- expect(applyValidationRules(createResult({ responseTimeMs: 101 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ responseTimeMs: 100 }), [rule])).toEqual([
- "Response time 100ms is not greater than 100ms",
- ]);
- expect(applyValidationRules(createResult({ responseTimeMs: 99 }), [rule])).toEqual([
- "Response time 99ms is not greater than 100ms",
- ]);
- });
- });
-
- describe("response_size", () => {
- it("'less_than' fails exactly at the threshold and passes just below", () => {
- const rule: ValidationRule = { type: "response_size", operator: "less_than", value: 2048 };
- expect(applyValidationRules(createResult({ bodySizeBytes: 2047 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ bodySizeBytes: 2048 }), [rule])).toEqual([
- "Response size 2048 bytes is not less than 2048 bytes",
- ]);
- });
-
- it("'greater_than' fails exactly at the threshold and passes just above", () => {
- const rule: ValidationRule = { type: "response_size", operator: "greater_than", value: 100 };
- expect(applyValidationRules(createResult({ bodySizeBytes: 101 }), [rule])).toEqual([]);
- expect(applyValidationRules(createResult({ bodySizeBytes: 100 }), [rule])).toEqual([
- "Response size 100 bytes is not greater than 100 bytes",
- ]);
- });
- });
-
- describe("response_body_contains", () => {
- it("passes when the body contains the value and fails when it does not", () => {
- const rule: ValidationRule = { type: "response_body_contains", value: "OK" };
- expect(applyValidationRules(createResult(), [rule], "status: OK")).toEqual([]);
- expect(applyValidationRules(createResult(), [rule], "status: down")).toEqual([
- 'Response body does not contain "OK"',
- ]);
- });
-
- it("is case sensitive by default and case insensitive when caseSensitive is false", () => {
- expect(applyValidationRules(createResult(), [{ type: "response_body_contains", value: "OK" }], "ok")).toEqual([
- 'Response body does not contain "OK"',
- ]);
- expect(
- applyValidationRules(
- createResult(),
- [{ type: "response_body_contains", value: "OK", caseSensitive: false }],
- "ok"
- )
- ).toEqual([]);
- });
-
- it("fails with a dedicated error when the body is empty", () => {
- const rule: ValidationRule = { type: "response_body_contains", value: "OK" };
- expect(applyValidationRules(createResult(), [rule], undefined)).toEqual(["Response body is empty"]);
- expect(applyValidationRules(createResult(), [rule], "")).toEqual(["Response body is empty"]);
- });
- });
-
- describe("response_body_not_contains", () => {
- it("passes when absent and fails when present", () => {
- const rule: ValidationRule = { type: "response_body_not_contains", value: "error" };
- expect(applyValidationRules(createResult(), [rule], "all good")).toEqual([]);
- expect(applyValidationRules(createResult(), [rule], "fatal error occurred")).toEqual([
- 'Response body contains "error"',
- ]);
- });
-
- it("passes when the body is empty", () => {
- const rule: ValidationRule = { type: "response_body_not_contains", value: "error" };
- expect(applyValidationRules(createResult(), [rule], undefined)).toEqual([]);
- });
-
- it("respects caseSensitive: false", () => {
- expect(
- applyValidationRules(
- createResult(),
- [{ type: "response_body_not_contains", value: "ERROR", caseSensitive: false }],
- "an error occurred"
- )
- ).toEqual(['Response body contains "ERROR"']);
- });
- });
-
- describe("header_exists", () => {
- it("matches header names case-insensitively", () => {
- const result = createResult({ headers: { "Content-Type": "application/json" } });
- expect(applyValidationRules(result, [{ type: "header_exists", header: "content-type" }])).toEqual([]);
- expect(applyValidationRules(result, [{ type: "header_exists", header: "CONTENT-TYPE" }])).toEqual([]);
- });
-
- it("fails when the header is missing", () => {
- const result = createResult({ headers: { "Content-Type": "application/json" } });
- expect(applyValidationRules(result, [{ type: "header_exists", header: "X-Request-Id" }])).toEqual([
- 'Header "X-Request-Id" does not exist',
- ]);
- });
-
- it("fails when no header name is specified", () => {
- expect(applyValidationRules(createResult(), [{ type: "header_exists" }])).toEqual(["Header name not specified"]);
- });
- });
-
- describe("header_value", () => {
- const result = createResult({ headers: { "Content-Type": "Application/JSON" } });
-
- it("matches header names case-insensitively but values case-sensitively for 'equals'", () => {
- expect(
- applyValidationRules(result, [
- { type: "header_value", header: "content-type", operator: "equals", value: "Application/JSON" },
- ])
- ).toEqual([]);
- expect(
- applyValidationRules(result, [
- { type: "header_value", header: "content-type", operator: "equals", value: "application/json" },
- ])
- ).toEqual(['Header "content-type" value "Application/JSON" does not equal "application/json"']);
- });
-
- it("supports 'contains' on the header value, case-sensitively", () => {
- expect(
- applyValidationRules(result, [
- { type: "header_value", header: "Content-Type", operator: "contains", value: "JSON" },
- ])
- ).toEqual([]);
- expect(
- applyValidationRules(result, [
- { type: "header_value", header: "Content-Type", operator: "contains", value: "json" },
- ])
- ).toEqual(['Header "Content-Type" value "Application/JSON" does not contain "json"']);
- });
-
- it("fails when the header is missing or unnamed", () => {
- expect(
- applyValidationRules(result, [{ type: "header_value", header: "X-Missing", operator: "equals", value: "x" }])
- ).toEqual(['Header "X-Missing" does not exist']);
- expect(applyValidationRules(result, [{ type: "header_value", operator: "equals", value: "x" }])).toEqual([
- "Header name not specified",
- ]);
- });
- });
-
- describe("rule combination and error handling", () => {
- it("evaluates every rule and collects all failures in rule order", () => {
- const rules: ValidationRule[] = [
- { type: "status_code", operator: "equals", value: 200 },
- { type: "response_time", operator: "less_than", value: 100 },
- { type: "response_body_contains", value: "healthy" },
- ];
- const result = createResult({ statusCode: 503, responseTimeMs: 250 });
-
- // All rules run: a failure does not short-circuit the remaining rules.
- expect(applyValidationRules(result, rules, "service degraded")).toEqual([
- "Status code 503 does not equal 200",
- "Response time 250ms is not less than 100ms",
- 'Response body does not contain "healthy"',
- ]);
- });
-
- it("only reports the rules that fail", () => {
- const rules: ValidationRule[] = [
- { type: "status_code", operator: "equals", value: 200 },
- { type: "response_body_contains", value: "down" },
- ];
- expect(applyValidationRules(createResult(), rules, "system is down")).toEqual([]);
- });
-
- it("reports unknown rule types as errors", () => {
- expect(applyValidationRules(createResult(), [{ type: "certificate" as ValidationRule["type"] }])).toEqual([
- "Unknown validation rule type: certificate",
- ]);
- });
-
- it("converts a thrown validator error into a validation error instead of aborting", () => {
- // headers is typed as Record<string, string>, but a malformed result at runtime
- // (headers undefined) makes Object.keys throw; the engine catches it and keeps
- // evaluating the remaining rules.
- const broken = createResult({ headers: undefined as unknown as Record<string, string>, statusCode: 500 });
- const errors = applyValidationRules(broken, [
- { type: "header_exists", header: "Content-Type" },
- { type: "status_code", operator: "equals", value: 200 },
- ]);
-
- expect(errors).toHaveLength(2);
- expect(errors[0]).toMatch(/^Validation rule error: /);
- expect(errors[1]).toBe("Status code 500 does not equal 200");
- });
- });
-});
diff --git a/server/src/services/uptime/validationEngine.ts b/server/src/services/uptime/validationEngine.ts
deleted file mode 100644
index 2a62657cc..000000000
--- a/server/src/services/uptime/validationEngine.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import { HttpCheckResult, ValidationRule } from "./types.js";
-
-export function applyValidationRules(
- result: HttpCheckResult,
- rules: ValidationRule[],
- responseBody?: string
-): string[] {
- const errors: string[] = [];
-
- for (const rule of rules) {
- try {
- const error = validateRule(result, rule, responseBody);
- if (error) {
- errors.push(error);
- }
- } catch (e) {
- errors.push(`Validation rule error: ${e instanceof Error ? e.message : "Unknown error"}`);
- }
- }
-
- return errors;
-}
-
-function validateRule(result: HttpCheckResult, rule: ValidationRule, responseBody?: string): string | null {
- switch (rule.type) {
- case "status_code":
- // Fail closed: a missing status code means the check never got a response,
- // so a status_code expectation cannot be considered satisfied.
- if (!result.statusCode) return "No status code available to validate";
- return validateStatusCode(result.statusCode, rule);
-
- case "response_time":
- return validateResponseTime(result.responseTimeMs, rule);
-
- case "response_body_contains":
- if (!responseBody) return "Response body is empty";
- return validateBodyContains(responseBody, rule, true);
-
- case "response_body_not_contains":
- if (!responseBody) return null;
- return validateBodyContains(responseBody, rule, false);
-
- case "header_exists":
- return validateHeaderExists(result.headers, rule);
-
- case "header_value":
- return validateHeaderValue(result.headers, rule);
-
- case "response_size":
- return validateResponseSize(result.bodySizeBytes, rule);
-
- default:
- return `Unknown validation rule type: ${rule.type}`;
- }
-}
-
-function validateStatusCode(statusCode: number, rule: ValidationRule): string | null {
- const value = rule.value;
-
- switch (rule.operator) {
- case "equals":
- if (statusCode !== value) {
- return `Status code ${statusCode} does not equal ${value}`;
- }
- break;
-
- case "not_equals":
- if (statusCode === value) {
- return `Status code ${statusCode} equals ${value}`;
- }
- break;
-
- case "in":
- // Fail closed: a non-array operand is a misconfigured rule, not a pass.
- if (!Array.isArray(value)) {
- return `Validation rule misconfigured: "in" operator requires an array value`;
- }
- if (!value.includes(statusCode)) {
- return `Status code ${statusCode} is not in [${value.join(", ")}]`;
- }
- break;
-
- case "not_in":
- // Fail closed: a non-array operand is a misconfigured rule, not a pass.
- if (!Array.isArray(value)) {
- return `Validation rule misconfigured: "not_in" operator requires an array value`;
- }
- if (value.includes(statusCode)) {
- return `Status code ${statusCode} is in [${value.join(", ")}]`;
- }
- break;
- }
-
- return null;
-}
-
-function validateResponseTime(responseTimeMs: number, rule: ValidationRule): string | null {
- const value = rule.value as number;
-
- switch (rule.operator) {
- case "less_than":
- if (responseTimeMs >= value) {
- return `Response time ${responseTimeMs}ms is not less than ${value}ms`;
- }
- break;
-
- case "greater_than":
- if (responseTimeMs <= value) {
- return `Response time ${responseTimeMs}ms is not greater than ${value}ms`;
- }
- break;
- }
-
- return null;
-}
-
-function validateBodyContains(body: string, rule: ValidationRule, shouldContain: boolean): string | null {
- const searchValue = String(rule.value);
- const caseSensitive = rule.caseSensitive !== false;
-
- const bodyToSearch = caseSensitive ? body : body.toLowerCase();
- const valueToSearch = caseSensitive ? searchValue : searchValue.toLowerCase();
-
- const contains = bodyToSearch.includes(valueToSearch);
-
- if (shouldContain && !contains) {
- return `Response body does not contain "${searchValue}"`;
- } else if (!shouldContain && contains) {
- return `Response body contains "${searchValue}"`;
- }
-
- return null;
-}
-
-function validateHeaderExists(headers: Record<string, string>, rule: ValidationRule): string | null {
- if (!rule.header) return "Header name not specified";
-
- const headerKey = Object.keys(headers).find(key => key.toLowerCase() === rule.header!.toLowerCase());
-
- if (!headerKey) {
- return `Header "${rule.header}" does not exist`;
- }
-
- return null;
-}
-
-function validateHeaderValue(headers: Record<string, string>, rule: ValidationRule): string | null {
- if (!rule.header) return "Header name not specified";
-
- const headerKey = Object.keys(headers).find(key => key.toLowerCase() === rule.header!.toLowerCase());
-
- if (!headerKey) {
- return `Header "${rule.header}" does not exist`;
- }
-
- const headerValue = headers[headerKey];
- const expectedValue = String(rule.value);
-
- switch (rule.operator) {
- case "equals":
- if (headerValue !== expectedValue) {
- return `Header "${rule.header}" value "${headerValue}" does not equal "${expectedValue}"`;
- }
- break;
-
- case "contains":
- if (!headerValue.includes(expectedValue)) {
- return `Header "${rule.header}" value "${headerValue}" does not contain "${expectedValue}"`;
- }
- break;
- }
-
- return null;
-}
-
-function validateResponseSize(sizeBytes: number, rule: ValidationRule): string | null {
- const value = rule.value as number;
-
- switch (rule.operator) {
- case "less_than":
- if (sizeBytes >= value) {
- return `Response size ${sizeBytes} bytes is not less than ${value} bytes`;
- }
- break;
-
- case "greater_than":
- if (sizeBytes <= value) {
- return `Response size ${sizeBytes} bytes is not greater than ${value} bytes`;
- }
- break;
- }
-
- return null;
-}