Compare commits

...
Author SHA1 Message Date
gorkem-bwl f85903adc9 chore(docs): trigger Vercel rebuild 2026-05-22 14:30:52 -04:00
gorkem-bwl a7895cce32 fix(docs): serve docs site at root of Vercel domain
Astro's base option was set to /docs to anticipate the reverse-proxy
URL at checkmate.so/docs. Vercel serves the dist folder at the root,
which made every page 404 because Astro had baked /docs/ into every
internal link and asset URL.

## Changes
- Remove base: "/docs" from astro.config.mjs — site now serves at root
- Update Releases nav link to /releases
- Update README's reverse-proxy snippet to strip the /docs prefix
  before forwarding to Vercel

## Final URL behaviour
- Direct: https://<vercel-domain>/                  → Introduction
- Direct: https://<vercel-domain>/releases/         → Releases
- Proxy:  https://checkmate.so/docs/                → strip /docs → Introduction
- Proxy:  https://checkmate.so/docs/releases/       → strip /docs → Releases
2026-05-22 14:26:51 -04:00
gorkem-bwl 8e4e9dd87c fix(docs): make the build self-contained for Vercel
Vercel's "Root Directory" setting limits the upload to docs/api/, so
the build cannot read sibling paths like ../../server/openapi.json or
../api-content/. A small prebuild script copies both into a vendored
folder inside the project tree (gitignored).

## Changes
- Add scripts/sync-sources.mjs to copy /docs/api-content/ and
  /server/openapi.json into docs/api/src/vendored/ before dev/build
- Wire predev/prebuild npm scripts so the sync runs automatically
- Update astro.config.mjs and src/content.config.ts to read from the
  vendored paths
- Gitignore src/vendored/ — contributors still edit the originals
2026-05-22 14:20:10 -04:00
gorkem-bwl 0d25973efb fix(docs): make the Starlight build pass
## Changes
- Bump @astrojs/starlight to ^0.32.0 so starlight-openapi 0.13's plugin
  contract (top-level setup hook) is supported
- Replace the no-arg docsLoader call with Astro's glob loader pointing
  at ../api-content so prose stays outside the Astro project tree
- Rename introduction.md → index.md and update the sidebar slug so the
  /docs/ root resolves instead of returning 404
- Commit package-lock.json so Vercel installs deterministically

## Verification
- npm run build produces 96 pages (7 narrative + 88 OpenAPI operations + 1
  releases timeline)
- /docs/, /docs/releases/, /docs/api-reference/operations/authlogin/ and
  every other route return 200 locally
- 14 release cards render with the brand-green "Latest" badge on v3.7.1
2026-05-22 14:04:52 -04:00
gorkem-bwl e69f40fdd0 docs(api): add releases timeline page
## Changes
- Add a Releases tab to the top navigation via a custom Starlight
  Header override (HeaderLinks.astro)
- Add ReleaseCard.astro — Vercel/Linear-style entry with sticky date
  + version on the left, headline and feature bullets on the right
- Curate 14 release entries spanning v1.0 (Sept 2024) through v3.7.1
  (April 2026), each focused on the most important user-facing
  features rather than every commit
- Newest release carries a "Latest" badge in the brand color
- Mobile layout collapses the two-column timeline to a single column

## Benefits
- Visitors can see at a glance what shipped recently and what
  Checkmate has matured into over time
- The data file (src/data/releases.ts) is the only thing that needs
  editing when a new version ships — no template or styling churn
- Built on the same Starlight site as the API docs, so look and feel
  stay consistent
2026-05-22 10:25:06 -04:00
gorkem-bwl 9aa2594df7 docs(api): add public API documentation site (Astro Starlight)
## Changes
- Add narrative API documentation in docs/api-content/ (introduction,
  quickstart, authentication, conventions, errors, rate limiting)
- Scaffold Astro Starlight site at docs/api/ that consumes prose from
  the sibling api-content folder and auto-generates the endpoint
  reference from server/openapi.json via starlight-openapi
- Wire Checkmate brand color (#13715B) into Starlight via custom CSS
- Add vercel.json so the docs site deploys cleanly as an Astro project
  with root directory docs/api/

## Benefits
- Public API docs ready to publish at checkmate.so/docs
- Endpoint reference stays in sync with the OpenAPI spec automatically
- Zero third-party SaaS dependency: site is fully self-hosted on Vercel
- Contributors edit plain markdown; no Astro knowledge needed for prose
2026-05-22 10:21:10 -04:00
ashu130698 9027707c92 chore: clean up deprecated FloatingActionBar component 2026-05-14 16:24:51 +05:30
ashu130698 9e69d863df fix(ui): remove unused SPACING import in monitors index 2026-05-14 15:54:55 +05:30
ashu130698 c740fb1aca fix(ui): resolve PR feedback regarding type casts and hardcoded spacing 2026-05-14 15:50:56 +05:30
ashu130698 3c05b9df98 fix(i18n): migrate and insert missing translation keys for bulk edit notifications 2026-05-14 15:49:16 +05:30
ashu130698 d5d79a1eda fix(ux): replace buggy margin-based centering with reliable flexbox wrapper to permanently center floating action bars 2026-05-14 15:49:16 +05:30
ashu130698 2097bc477a fix(ux): replace overwritten transform on floating action bars to fix overflow centering on mobile devices 2026-05-14 15:49:16 +05:30
ashu130698 744d8c8dcf style: fix code format issues 2026-05-14 15:49:16 +05:30
ashu130698 7a5ee6ba05 fix(monitors): address PR feedback on mobile card views and modal selection state 2026-05-14 15:48:55 +05:30
ashu130698 eeee6db94e fix(monitors): add missing page prop to MonitorTable 2026-05-14 15:46:55 +05:30
ashu130698 656c04d0e4 fix(monitors): PR feedback -layout rhythm, pagination memory leak, error alerts, and mobile cards 2026-05-14 15:46:33 +05:30
ashu130698 010ef9661f fix: corrected TypeScript notification property name 2026-05-14 15:45:30 +05:30
ashu130698 ff0ef928a6 feat: added bulk edit notification UI to uptime monitors 2026-05-14 15:45:11 +05:30
ashu130698 eb29a725c2 feat: add table row selection and floating action bar MVP 2026-05-14 15:41:50 +05:30
Alexander Holliday 72f23ca025 Merge pull request #3547 from ZeinebMegaadi/fix/maintenance-recurring-edit-validation
Fix/maintenance recurring edit validation
2026-05-13 11:41:38 -07:00
Alexander Holliday ae9416641c Merge pull request #3652 from bluewave-labs/fix/findByIdsWithChecks
fix: update query
2026-05-13 11:29:02 -07:00
Alex Holliday b7844f8b10 update query 2026-05-13 11:26:25 -07:00
Alexander Holliday ffb563f36d Merge pull request #3650 from bluewave-labs/feat/fe/maintenance-window-groups
Feat/fe/maintenance window groups
2026-05-12 11:21:05 -07:00
Alexander Holliday ae5115a38f Merge pull request #3649 from bluewave-labs/feat/maintenance-window-groups
feat: maintenance window groups
2026-05-12 11:20:51 -07:00
Alex Holliday b925434078 tighten validation, add tests 2026-05-12 11:18:51 -07:00
Alex Holliday f713698572 update maintenacne window hook and form 2026-05-12 11:06:26 -07:00
Alex Holliday 47d2b62e92 update type 2026-05-12 10:58:03 -07:00
Alex Holliday 780189e4a1 add migrations 2026-05-12 10:53:40 -07:00
Alex Holliday f86ceae0c6 update tests 2026-05-12 10:41:30 -07:00
Alex Holliday e78524d1c9 udpate service to use monitorIds instead of monitorId 2026-05-12 10:39:05 -07:00
Alex Holliday 7a2dab6cc4 update repository toEntity method 2026-05-12 10:38:47 -07:00
Alex Holliday c90442b49f update maintenance window type to match DB model 2026-05-12 10:38:22 -07:00
Alex Holliday bdecc1a5e2 update maintenance window model to use array of IDs instead of ID 2026-05-12 10:37:59 -07:00
Alexander Holliday c1fc537479 Merge pull request #3648 from bluewave-labs/fix/histogram-response-time
fix: histogram-response-times
2026-05-12 09:52:49 -07:00
Alex Holliday 6f0540fb33 properly type payload, avgResponseTime -> originalAvgResponseTime 2026-05-12 09:41:58 -07:00
Alexander Holliday 3876aae484 Merge pull request #3645 from bluewave-labs/fix/husky-merge-guard
fix: husky guard pre-commit against merge/rebase state
2026-05-11 11:39:36 -07:00
AlexandClaude Opus 4.7 2f646ee154 fix(husky): guard pre-commit against merge/rebase state
lint-staged uses git stash internally to isolate staged files for
linting. During a merge/rebase/cherry-pick/revert, that stash machinery
interacts catastrophically with MERGE_HEAD and friends — on any lint
failure it resets, silently wiping MERGE_HEAD and your conflict
resolutions. The user ends up in a loop where every merge attempt
leaves a clean tree with no merge commit.

This adds an early-exit guard for the four mid-operation states, and
also anchors the script to the repo root + scopes each lint-staged run
in a subshell so a subdir commit or per-package failure can't poison
the cwd for the next step.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 11:37:23 -07:00
Alexander Holliday 01da5847f0 Merge pull request #3470 from bluewave-labs/feat/pagespeed-mobile-strat
feat: adding mobile/desktop pagespeed strategy
2026-05-11 11:34:11 -07:00
Alex 4b888c1ed1 bump dependencies 2026-05-11 11:30:58 -07:00
Alex 6b63091d89 tighten validation, add tests 2026-05-11 11:28:39 -07:00
Alex 78fdc548bb Merge remote-tracking branch 'origin/develop' into feat/pagespeed-mobile-strat 2026-05-11 11:11:13 -07:00
Alexander Holliday bbdbe75255 Merge pull request #3584 from Iriome-Santana/fix/non-root-container-support
fix: allow mono and arm containers to run as non-root user (UID 1000)
2026-05-11 10:38:42 -07:00
Alexander Holliday 74bc5accb6 Merge pull request #3644 from bluewave-labs/feat/fe/dns-monitors
feat: fe/dns monitors
2026-05-11 10:32:39 -07:00
Alex 60770a4544 udpate monitor path map 2026-05-11 10:29:59 -07:00
Alex 766d847561 tighten validation, replace negative type checks with allowed list 2026-05-11 10:27:41 -07:00
Alex 08043a5ea0 tighten validation, add tests 2026-05-11 10:12:27 -07:00
Alex 272e4b5014 update server services to support DNS type queries 2026-05-11 10:01:42 -07:00
Alex 98d2bbfbb9 add DNS monitor to create monitor form 2026-05-11 10:01:23 -07:00
Alex 427f8c632f update validation to include dnsServer and dnsRecordType 2026-05-11 10:01:04 -07:00
Alex 9a004ab1fb udpate monitor types to include DNS, add dnsRecordType 2026-05-11 09:59:53 -07:00
Alexander Holliday c9b9c4a53f Merge pull request #3643 from adosaiguas/develop
i18n: add Catalan language
2026-05-09 09:41:08 -07:00
Agustí Dosaiguas db746b0ff2 Merge branch 'bluewave-labs:develop' into develop 2026-05-09 18:15:31 +02:00
Agustí Dosaiguas 80fca45ce8 i18n: add Catalan language 2026-05-09 18:13:45 +02:00
Iriome 53c58eb945 fix: make non-root support opt-in, keep root as default
Remove USER node directive so existing deployments are unaffected.
The chown ensures --user 1000 works without changing the default behaviour.
2026-05-01 21:56:40 +01:00
Iriome 49fcab2ee3 fix: allow containers to run as non-root user (UID 1000)
- chown public/, dist/, and scripts/ to node:node after build
- add USER node directive before EXPOSE in dist-mono and dist-arm Dockerfiles
- update CMD to exec form in dist-mono for consistency

Fixes running the container with --user 1000 in environments that
don't allow containers to run as root. The sed -i in inject-vars.sh
requires write permission on ./public/assets/, which previously
failed with 'Permission denied' when running as non-root.

The node user (UID 1000) is built into the node:20-slim base image.
Existing root deployments are unaffected.
2026-04-27 14:40:51 +01:00
ZeinebMegaadi d41d9a3dab fix: skip future date validation when editing maintenance window 2026-04-18 12:55:10 +01:00
ZeinebMegaadi 1a54a24fd5 fix: skip future date validation when editing maintenance window 2026-04-18 12:54:13 +01:00
mannilakash ac51dfeab7 fix: removing default value for strategy - monitors 2026-04-13 13:17:24 -04:00
mannilakash 99a5aa1722 fix: badge and timescaleDB changes 2026-04-13 08:29:12 -04:00
mannilakash 5791bdd5e7 fix: adding timescaledb changes 2026-04-07 07:25:35 -04:00
mannilakash f7514bc938 fix: format errors 2026-04-07 07:14:17 -04:00
mannilakash 2bbaf7d1eb feat: adding mobile/desktop pagespeed strategy 2026-04-07 07:02:44 -04:00
71 changed files with 12271 additions and 278 deletions

No files matched your search

Regular → Executable
+21 -2
View File
@@ -1,4 +1,23 @@
#!/bin/sh
# Skip during merge/rebase/cherry-pick/revert. lint-staged's internal
# git-stash mechanism is incompatible with these states and will silently
# wipe MERGE_HEAD and your conflict resolutions on commit failure.
git_dir=$(git rev-parse --git-dir)
if [ -e "$git_dir/MERGE_HEAD" ] \
|| [ -e "$git_dir/CHERRY_PICK_HEAD" ] \
|| [ -e "$git_dir/REVERT_HEAD" ] \
|| [ -d "$git_dir/rebase-merge" ] \
|| [ -d "$git_dir/rebase-apply" ]; then
echo "Skipping lint-staged (mid merge/rebase/cherry-pick/revert)"
exit 0
fi
# Anchor to repo root so commits made from a subdirectory still work, and
# run each package's lint-staged in a subshell so cwd is scoped (a failure
# inside one package can't poison the cwd for the next).
cd "$(git rev-parse --show-toplevel)" || exit 1
echo "Running lint-staged..."
cd client && npx lint-staged && cd ..
cd server && npx lint-staged && cd ..
(cd client && npx lint-staged) || exit 1
(cd server && npx lint-staged) || exit 1
@@ -1,12 +1,13 @@
import type { Monitor } from "@/Types/Monitor";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { PulseDot, Dot } from "@/Components/design-elements";
import { PulseDot, Dot, StrategyBadge } from "@/Components/design-elements";
import { getStatusColor, formatUrl } from "@/Utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
import prettyMilliseconds from "pretty-ms";
import { typographyLevels } from "@/Utils/Theme/Palette";
import useMediaQuery from "@mui/material/useMediaQuery";
import { LAYOUT } from "@/Utils/Theme/constants";
export const MonitorStatus = ({ monitor }: { monitor: Monitor }) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
@@ -28,7 +29,7 @@ export const MonitorStatus = ({ monitor }: { monitor: Monitor }) => {
<Stack
direction="row"
alignItems={"center"}
gap={theme.spacing(4)}
gap={theme.spacing(LAYOUT.XS)}
>
<PulseDot color={getStatusColor(monitor.status, theme)} />
<Typography
@@ -41,6 +42,12 @@ export const MonitorStatus = ({ monitor }: { monitor: Monitor }) => {
>
{formatUrl(monitor?.url)}
</Typography>
{monitor.type === "pagespeed" && monitor.strategy && (
<>
<Dot />
<StrategyBadge strategy={monitor.strategy} />
</>
)}
{!isSmall && (
<>
<Dot />
@@ -0,0 +1,32 @@
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import type { PageSpeedStrategy } from "@/Types/Monitor";
import { SPACING } from "@/Utils/Theme/constants";
interface StrategyBadgeProps {
strategy: PageSpeedStrategy | undefined;
variant?: "caption" | "body2";
}
export const StrategyBadge = ({ strategy, variant = "body2" }: StrategyBadgeProps) => {
const theme = useTheme();
const { t } = useTranslation();
if (!strategy) {
return null;
}
return (
<Typography
variant={variant}
px={SPACING.XXL}
py={SPACING.SM}
borderRadius={theme.shape.borderRadius}
bgcolor={theme.palette.secondary.light}
color={theme.palette.text.primary}
>
{t(`pages.pageSpeed.strategy.${strategy}`)}
</Typography>
);
};
@@ -142,7 +142,7 @@ export function DataTable<
>
<Typography
component="div"
color={theme.palette.text.primary}
color={theme.palette.text.secondary}
>
{header.mobileLabel ?? header.content}
</Typography>
@@ -26,3 +26,4 @@ export * from "./NoticeBanner";
export * from "./OfflineBanner";
export * from "./Avatar";
export * from "./StatusCodeLabel";
export * from "./StrategyBadge";
@@ -10,6 +10,7 @@ import type { RootState } from "@/Types/state";
export const languageNames: Record<string, string> = {
en: "English",
de: "Deutsch",
ca: "Català",
es: "Español",
fr: "Français",
"pt-BR": "Português (BR)",
@@ -0,0 +1,138 @@
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { Dialog, Select, RadioWithDescription } from "@/Components/inputs";
import { SPACING, LAYOUT } from "@/Utils/Theme/constants";
import Stack from "@mui/material/Stack";
import RadioGroup from "@mui/material/RadioGroup";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import Alert from "@mui/material/Alert";
import { useGet, usePatch } from "@/Hooks/UseApi";
import type { Notification } from "@/Types/Notification";
interface BulkEditNotificationsModalProps {
open: boolean;
onClose: () => void;
selectedMonitors: string[];
onComplete: (success: boolean) => void;
}
export const BulkEditNotificationsModal: React.FC<BulkEditNotificationsModalProps> = ({
open,
onClose,
selectedMonitors,
onComplete,
}) => {
const { t } = useTranslation();
const theme = useTheme();
const [action, setAction] = useState<"add" | "remove" | "set">("add");
const [notificationIds, setNotificationIds] = useState<string[]>([]);
// Fetch available notifications
const { data: notifications } = useGet<Notification[]>(
"/notifications/team",
undefined,
{
keepPreviousData: true,
}
);
const { patch, loading: isPatching, error } = usePatch();
// Reset state when modal opens
useEffect(() => {
if (open) {
setAction("add");
setNotificationIds([]);
}
}, [open]);
const handleConfirm = async () => {
const res = await patch("/monitors/notifications", {
monitorIds: selectedMonitors,
notificationIds,
action,
});
onComplete(!!res);
};
// Prevent submitting empty arrays unless the action is 'set'
const isMissingSelection = action !== "set" && notificationIds.length === 0;
return (
<Dialog
open={open}
title={t("pages.common.monitors.bulkEdit.title")}
onCancel={onClose}
onConfirm={isMissingSelection ? undefined : handleConfirm}
loading={isPatching}
maxWidth="sm"
fullWidth
>
<Stack
spacing={theme.spacing(LAYOUT.XS)}
mt={theme.spacing(SPACING.LG)}
>
{error && <Alert severity="error">{error}</Alert>}
<Typography variant="body1">
{t("pages.common.monitors.bulkEdit.selectedText", {
count: selectedMonitors.length,
})}
</Typography>
<RadioGroup
value={action}
onChange={(e) => {
const val = e.target.value;
if (val === "add" || val === "remove" || val === "set") {
setAction(val);
}
}}
>
<RadioWithDescription
value="add"
label={t("pages.common.monitors.bulkEdit.actionAdd")}
description={t("pages.common.monitors.bulkEdit.actionAddDesc")}
/>
<RadioWithDescription
value="remove"
label={t("pages.common.monitors.bulkEdit.actionRemove")}
description={t("pages.common.monitors.bulkEdit.actionRemoveDesc")}
/>
<RadioWithDescription
value="set"
label={t("pages.common.monitors.bulkEdit.actionSet")}
description={t("pages.common.monitors.bulkEdit.actionSetDesc")}
/>
</RadioGroup>
<Select
multiple
value={notificationIds}
onChange={(e) => {
const val = e.target.value;
if (typeof val === "string") {
setNotificationIds(val.split(","));
} else if (Array.isArray(val)) {
setNotificationIds(val.filter((v) => typeof v === "string"));
}
}}
fieldLabel={t("pages.common.monitors.bulkEdit.selectLabel")}
placeholder={t("pages.common.monitors.bulkEdit.selectPlaceholder")}
>
{notifications?.map((n) => (
<MenuItem
key={n.id}
value={n.id}
>
{n.notificationName} ({n.type.toUpperCase()})
</MenuItem>
))}
</Select>
</Stack>
</Dialog>
);
};
@@ -9,6 +9,8 @@ import {
ResponsiveContainer,
Text,
} from "recharts";
import type { TooltipProps } from "recharts";
import type { NameType, ValueType } from "recharts/types/component/DefaultTooltipContent";
import Typography from "@mui/material/Typography";
import { useSelector } from "react-redux";
@@ -18,13 +20,14 @@ import {
tooltipDateFormatLookup,
} from "@/Utils/TimeUtils";
import { useTheme } from "@mui/material/styles";
import type { Theme } from "@mui/material/styles";
import type { GroupedCheck } from "@/Types/Check";
import type { RootState } from "@/Types/state";
type XTickProps = {
x: number;
y: number;
payload: { value: any };
payload: { value: string };
range: string;
};
@@ -46,12 +49,9 @@ export const XTick = ({ x, y, payload, range }: XTickProps) => {
);
};
type ResponseTimeToolTipProps = {
active?: boolean | undefined;
payload?: any[];
label?: string | number;
type ResponseTimeToolTipProps = TooltipProps<ValueType, NameType> & {
range: string;
theme: any;
theme: Theme;
uiTimezone: string;
};
@@ -68,7 +68,8 @@ const ResponseTimeToolTip = ({
if (!active) return null;
const format = tooltipDateFormatLookup(range);
const responseTime = Math.floor(payload?.[0]?.payload?.avgResponseTime || 0);
console.log(payload);
const responseTime = Math.floor(payload[0]?.payload?.originalAvgResponseTime || 0);
return (
<BaseBox sx={{ py: theme.spacing(2), px: theme.spacing(4) }}>
<Typography>{formatDateWithTz(String(label), format, uiTimezone)}</Typography>
+1
View File
@@ -15,3 +15,4 @@ export * from "./charts/HistogramPageSpeedDetailsTooltip";
export * from "./charts/HistogramInfrastructure";
export * from "./HeaderMonitorsSummary";
export * from "./BulkActionsBar";
export * from "./BulkEditNotificationsModal";
+6 -2
View File
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import dayjs from "dayjs";
import {
maintenanceWindowSchema,
maintenanceWindowEditSchema,
repeatOptions,
type MaintenanceWindowFormData,
} from "@/Validation/maintenanceWindow";
@@ -32,7 +33,7 @@ export const useMaintenanceWindowForm = ({
startTime: startDate.format("HH:mm"),
duration: data.duration ?? 0,
durationUnit: data.durationUnit ?? "minutes",
monitors: [data.monitorId],
monitors: data.monitorIds,
};
} else {
const now = dayjs();
@@ -47,6 +48,9 @@ export const useMaintenanceWindowForm = ({
};
}
return { schema: maintenanceWindowSchema, defaults };
return {
schema: data ? maintenanceWindowEditSchema : maintenanceWindowSchema,
defaults,
};
}, [data]);
};
+11
View File
@@ -1,5 +1,6 @@
import { useMemo } from "react";
import { monitorSchema, type MonitorFormData } from "@/Validation/monitor";
import { DefaultPageSpeedStrategy } from "@/Types/Monitor";
import type { Monitor, MonitorType } from "@/Types/Monitor";
interface UseMonitorFormOptions {
@@ -88,6 +89,7 @@ export const useMonitorForm = ({
...base,
type: "pagespeed",
url: data?.url || "",
strategy: data?.strategy ?? DefaultPageSpeedStrategy,
};
break;
case "hardware":
@@ -111,6 +113,15 @@ export const useMonitorForm = ({
ignoreTlsErrors: data?.ignoreTlsErrors || false,
};
break;
case "dns":
defaults = {
...base,
type: "dns",
url: data?.url || "",
dnsServer: data?.dnsServer || "",
dnsRecordType: data?.dnsRecordType || "A",
};
break;
default:
defaults = {
...base,
+146 -1
View File
@@ -37,6 +37,7 @@ import {
type MonitorType,
type GamesMap,
supportsGeoCheck,
DefaultPageSpeedStrategy,
} from "@/Types/Monitor";
import type { Notification } from "@/Types/Notification";
import type { MonitorFormData } from "@/Validation/monitor";
@@ -51,6 +52,9 @@ interface GeneralSettingsConfig {
showSecret: boolean;
showGrpcServiceName: boolean;
showIgnoreTls: boolean;
showStrategy: boolean;
showDnsServer: boolean;
showDnsRecordType: boolean;
}
const getGeneralSettingsConfig = (
@@ -68,6 +72,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
ping: {
urlLabel: t("pages.createMonitor.form.general.option.host.label"),
@@ -79,6 +86,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
docker: {
urlLabel: t("pages.createMonitor.form.general.option.container.label"),
@@ -90,6 +100,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
port: {
urlLabel: t("pages.createMonitor.form.general.option.url.label"),
@@ -101,6 +114,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
game: {
urlLabel: t("pages.createMonitor.form.general.option.url.label"),
@@ -112,6 +128,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
grpc: {
urlLabel: t("pages.createMonitor.form.general.option.host.label"),
@@ -123,6 +142,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: true,
showIgnoreTls: true,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
pagespeed: {
urlLabel: t("pages.createMonitor.form.general.option.url.label"),
@@ -134,6 +156,9 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: true,
showDnsServer: false,
showDnsRecordType: false,
},
hardware: {
urlLabel: t("pages.createMonitor.form.general.option.captureUrl.label"),
@@ -145,6 +170,9 @@ const getGeneralSettingsConfig = (
showSecret: true,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
websocket: {
urlLabel: t("pages.createMonitor.form.general.option.wsUrl.label"),
@@ -156,6 +184,23 @@ const getGeneralSettingsConfig = (
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: true,
showStrategy: false,
showDnsServer: false,
showDnsRecordType: false,
},
dns: {
urlLabel: t("pages.createMonitor.form.general.option.url.label"),
urlPlaceholder: t("pages.createMonitor.form.general.option.url.placeholder"),
namePlaceholder: t("pages.createMonitor.form.general.option.name.placeholder"),
showUrl: true,
showPort: false,
showGameSelect: false,
showSecret: false,
showGrpcServiceName: false,
showIgnoreTls: false,
showStrategy: false,
showDnsServer: true,
showDnsRecordType: true,
},
};
return configs[type] || configs.http;
@@ -349,6 +394,13 @@ const CreateMonitorPage = () => {
"pages.createMonitor.form.type.optionWebSocketDescription"
)}
/>
<RadioWithDescription
value="dns"
label={t("pages.common.monitors.monitorTypes.optionDns")}
description={t(
"pages.createMonitor.form.type.optionDnsDescription"
)}
/>
</RadioGroup>
</FormControl>
)}
@@ -395,6 +447,31 @@ const CreateMonitorPage = () => {
/>
)}
{/* Strategy field - only for pagespeed type */}
{generalSettingsConfig.showStrategy && (
<Controller
name="strategy"
control={control}
render={({ field, fieldState }) => (
<Select
{...field}
value={field.value ?? DefaultPageSpeedStrategy}
fieldLabel={t(
"pages.createMonitor.form.general.option.strategy.label"
)}
error={!!fieldState.error}
>
<MenuItem value="desktop">
{t("pages.createMonitor.form.general.option.strategy.desktop")}
</MenuItem>
<MenuItem value="mobile">
{t("pages.createMonitor.form.general.option.strategy.mobile")}
</MenuItem>
</Select>
)}
/>
)}
{/* Port field - only for port and game types */}
{generalSettingsConfig.showPort && (
<Controller
@@ -495,6 +572,74 @@ const CreateMonitorPage = () => {
)}
/>
)}
{generalSettingsConfig.showDnsServer && (
<Controller
name="dnsServer"
control={control}
render={({ field, fieldState }) => (
<TextField
{...field}
value={field.value ?? ""}
type="text"
fieldLabel={t(
"pages.createMonitor.form.general.option.dnsServer.label"
)}
placeholder={t(
"pages.createMonitor.form.general.option.dnsServer.placeholder"
)}
fullWidth
error={!!fieldState.error}
helperText={fieldState.error?.message ?? ""}
/>
)}
/>
)}
{generalSettingsConfig.showDnsRecordType && (
<Controller
name="dnsRecordType"
control={control}
defaultValue="A"
render={({ field, fieldState }) => (
<Select
{...field}
value={field.value ?? "A"}
fieldLabel={t(
"pages.createMonitor.form.general.option.dnsRecordType.label"
)}
error={!!fieldState.error}
>
<MenuItem value={"A"}>
{t("pages.createMonitor.form.general.option.dnsRecordType.value.A")}
</MenuItem>
<MenuItem value={"AAAA"}>
{t(
"pages.createMonitor.form.general.option.dnsRecordType.value.AAAA"
)}
</MenuItem>
<MenuItem value={"CNAME"}>
{t(
"pages.createMonitor.form.general.option.dnsRecordType.value.CNAME"
)}
</MenuItem>
<MenuItem value={"MX"}>
{t(
"pages.createMonitor.form.general.option.dnsRecordType.value.MX"
)}
</MenuItem>
<MenuItem value={"NS"}>
{t(
"pages.createMonitor.form.general.option.dnsRecordType.value.NS"
)}
</MenuItem>
<MenuItem value={"TXT"}>
{t(
"pages.createMonitor.form.general.option.dnsRecordType.value.TXT"
)}
</MenuItem>
</Select>
)}
/>
)}
<Controller
name="name"
@@ -900,7 +1045,7 @@ const CreateMonitorPage = () => {
/>
<Typography
component="span"
color="text.secondary"
color={theme.palette.text.secondary}
sx={{ opacity: 0.8 }}
>
<Trans
@@ -22,6 +22,7 @@ import type { MaintenanceWindowFormData } from "@/Validation/maintenanceWindow";
import { repeatOptions, durationUnitOptions } from "@/Validation/maintenanceWindow";
import { useMaintenanceWindowForm } from "@/Hooks/useMaintenanceWindowForm";
import { useGet, usePost, usePatch } from "@/Hooks/UseApi";
import { mutate } from "swr";
import { useParams, useNavigate } from "react-router-dom";
import type { Monitor } from "@/Types/Monitor";
import { useForm, Controller } from "react-hook-form";
@@ -99,6 +100,9 @@ const CreateMaintenanceWindowPage = () => {
}
if (result?.success) {
await mutate(
(key) => typeof key === "string" && key.startsWith("/maintenance-window")
);
navigate("/maintenance");
}
};
@@ -1,7 +1,13 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/Components/design-elements";
import {
Table,
Pagination,
StatusLabel,
StrategyBadge,
} from "@/Components/design-elements";
import { LAYOUT } from "@/Utils/Theme/constants";
import { HistogramPageSpeed } from "@/Components/monitors";
import { ArrowDown, ArrowUp } from "lucide-react";
import type { Header } from "@/Components/design-elements/Table";
@@ -179,7 +185,19 @@ export const PageSpeedMonitorsTable = ({
</Stack>
),
render: (row) => {
return row.name;
return (
<Stack
direction="row"
alignItems="center"
gap={LAYOUT.XS}
>
<Typography>{row.name}</Typography>
<StrategyBadge
strategy={row.strategy}
variant="caption"
/>
</Stack>
);
},
},
{
@@ -13,6 +13,7 @@ import { ArrowDown, ArrowUp } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useNavigate } from "react-router-dom";
import { usePost } from "@/Hooks/UseApi";
import { useSelector } from "react-redux";
@@ -21,6 +22,7 @@ import type { Monitor } from "@/Types/Monitor";
import type { ActionMenuItem } from "@/Components/actions-menu";
import type { RootState } from "@/Types/state";
import { Checkbox } from "@/Components/inputs";
import { SPACING, LAYOUT } from "@/Utils/Theme/constants";
interface MonitorTableProps {
monitors: Monitor[];
@@ -57,6 +59,7 @@ export const MonitorTable = ({
}: MonitorTableProps) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const chartType = useSelector((state: RootState) => state.ui?.chartType ?? "histogram");
const { post } = usePost<Record<string, never>, Monitor>();
@@ -205,7 +208,7 @@ export const MonitorTable = ({
mobileLabel: t("common.table.headers.name"),
content: (
<Stack
gap={theme.spacing(4)}
gap={theme.spacing(LAYOUT.XS)}
direction={"row"}
alignItems={"center"}
onClick={(e) => handleSort(e, "name")}
@@ -225,14 +228,14 @@ export const MonitorTable = ({
mobileLabel: t("common.table.headers.status"),
content: (
<Stack
gap={theme.spacing(4)}
gap={theme.spacing(LAYOUT.XS)}
direction={"row"}
justifyContent={"center"}
alignItems={"center"}
onClick={(e) => handleSort(e, "status")}
sx={{ cursor: "pointer" }}
>
<Box width={theme.spacing(8)} />
<Box width={theme.spacing(LAYOUT.MD)} />
{t("common.table.headers.status")}
{renderSortIcon(sortField === "status")}
</Stack>
@@ -257,14 +260,14 @@ export const MonitorTable = ({
mobileLabel: t("common.table.headers.type"),
content: (
<Stack
gap={theme.spacing(4)}
gap={theme.spacing(LAYOUT.XS)}
direction={"row"}
justifyContent={"center"}
alignItems={"center"}
onClick={(e) => handleSort(e, "type")}
sx={{ cursor: "pointer" }}
>
<Box width={theme.spacing(8)} />
<Box width={theme.spacing(LAYOUT.MD)} />
{t("common.table.headers.type")}
{renderSortIcon(sortField === "type")}
</Stack>
@@ -288,6 +291,30 @@ export const MonitorTable = ({
return (
<Box>
{isSmall && (
<Box
px={SPACING.SM}
pb={SPACING.LG}
>
<Stack
direction="row"
alignItems="center"
spacing={SPACING.SM}
>
<Checkbox
checked={isAllSelected}
indeterminate={isSomeSelected}
onChange={(e) => handleSelectAll(e.target.checked)}
/>
<Typography
variant="body2"
color="text.secondary"
>
{t("pages.common.monitors.bulkEdit.selectAll", "Select All")}
</Typography>
</Stack>
</Box>
)}
<Table
headers={headers}
data={monitors}
+33 -5
View File
@@ -9,6 +9,7 @@ import Stack from "@mui/material/Stack";
import { MonitorTable } from "@/Pages/Uptime/Monitors/Components/UptimeMonitorsTable";
import { HeaderCreate } from "@/Components/common";
import { Play, Pause } from "lucide-react";
import { BulkEditNotificationsModal } from "@/Components/monitors";
import { useTranslation } from "react-i18next";
import useMediaQuery from "@mui/material/useMediaQuery";
@@ -22,6 +23,7 @@ import type { RootState } from "@/Types/state";
import { useTheme } from "@mui/material";
import useDebounce from "@/Hooks/useDebounce";
import { useBulkMonitorActions } from "@/Hooks/useBulkMonitorActions";
import { LAYOUT } from "@/Utils/Theme/constants";
const UptimeMonitorsPage = () => {
const { t } = useTranslation();
@@ -43,7 +45,7 @@ const UptimeMonitorsPage = () => {
const [sortField, setSortField] = useState<string>("");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
const [selectedMonitor, setSelectedMonitor] = useState<Monitor | null>(null);
const [isBulkEditModalOpen, setIsBulkEditModalOpen] = useState(false);
const isDialogOpen = Boolean(selectedMonitor);
const debouncedSearch = useDebounce<string>(search, 300);
@@ -77,7 +79,7 @@ const UptimeMonitorsPage = () => {
const effectiveTypes =
selectedTypes.length > 0
? selectedTypes
: ["http", "ping", "docker", "port", "game", "grpc", "websocket"];
: ["http", "ping", "docker", "port", "game", "grpc", "websocket", "dns"];
// Build URL for monitors with checks
const monitorsWithChecksUrl = useMemo(() => {
@@ -136,6 +138,14 @@ const UptimeMonitorsPage = () => {
refetch();
};
const handleBulkEditComplete = (success: boolean) => {
setIsBulkEditModalOpen(false);
if (success) {
setSelectedRows([]);
refetch();
}
};
const handleCancel = () => {
setSelectedMonitor(null);
};
@@ -174,7 +184,7 @@ const UptimeMonitorsPage = () => {
<Stack
direction={isSmall ? "column" : "row"}
justifyContent={isSmall ? "flex-start" : "space-between"}
gap={theme.spacing(4)}
gap={theme.spacing(LAYOUT.XS)}
>
<ControlsFilter
selectedTypes={selectedTypes}
@@ -213,16 +223,27 @@ const UptimeMonitorsPage = () => {
>
{t("common.buttons.pause")}
</Button>
<Button
size="small"
onClick={() => setIsBulkEditModalOpen(true)}
>
{t("pages.common.monitors.bulkEdit.editButton", {
defaultValue: "Edit Notifications",
})}
</Button>
</BulkActionsBar>
)}
<MonitorTable
page={page}
monitors={monitorsWithChecks || []}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count || 0}
page={page}
setPage={setPage}
setPage={(newPage) => {
setPage(newPage);
setSelectedRows([]);
}}
rowsPerPage={rowsPerPage}
sortField={sortField}
setSortField={setSortField}
@@ -236,6 +257,7 @@ const UptimeMonitorsPage = () => {
})
);
setPage(0);
setSelectedRows([]);
}}
selectedRows={selectedRows}
onSelectionChange={setSelectedRows}
@@ -248,6 +270,12 @@ const UptimeMonitorsPage = () => {
onCancel={handleCancel}
loading={isDeleting}
/>
<BulkEditNotificationsModal
open={isBulkEditModalOpen}
onClose={() => setIsBulkEditModalOpen(false)}
selectedMonitors={selectedRows}
onComplete={handleBulkEditComplete}
/>
</MonitorBasePageWithStates>
);
};
+1 -1
View File
@@ -2,7 +2,7 @@ export type DurationUnit = "seconds" | "minutes" | "hours" | "days";
export interface MaintenanceWindow {
id: string;
monitorId: string;
monitorIds: string[];
teamId: string;
active: boolean;
name: string;
+11
View File
@@ -15,10 +15,14 @@ export const MonitorTypes = [
"game",
"grpc",
"websocket",
"dns",
"unknown",
] as const;
export type MonitorType = (typeof MonitorTypes)[number];
export const DnsRecordTypes = ["A", "AAAA", "CNAME", "MX", "TXT", "NS"] as const;
export type DnsRecordType = (typeof DnsRecordTypes)[number];
export const GeoCheckSupportedTypes: readonly MonitorType[] = ["http", "ping"] as const;
export const supportsGeoCheck = (type: MonitorType | undefined): boolean => {
@@ -40,6 +44,10 @@ export type MonitorStatus = (typeof MonitorStatuses)[number];
export type MonitorMatchMethod = "equal" | "include" | "regex" | "";
export const PageSpeedStrategies = ["desktop", "mobile"] as const;
export type PageSpeedStrategy = (typeof PageSpeedStrategies)[number];
export const DefaultPageSpeedStrategy: PageSpeedStrategy = "desktop";
export interface Monitor {
id: string;
userId: string;
@@ -74,10 +82,13 @@ export interface Monitor {
selectedDisks: string[];
gameId?: string;
grpcServiceName?: string;
strategy?: PageSpeedStrategy;
group: string | null;
geoCheckEnabled?: boolean;
geoCheckLocations?: GeoContinent[];
geoCheckInterval?: number;
dnsServer?: string;
dnsRecordType?: DnsRecordType;
recentChecks: CheckSnapshot[];
createdAt: string;
updatedAt: string;
+1
View File
@@ -10,6 +10,7 @@ export const getMonitorPath = (type: MonitorType): string => {
game: "uptime",
grpc: "uptime",
websocket: "uptime",
dns: "uptime",
unknown: "uptime",
docker: "uptime",
hardware: "infrastructure",
+27 -25
View File
@@ -14,30 +14,32 @@ export const durationUnitOptions = [
{ id: "days", name: "days", multiplier: 86400000 },
] as const;
export const maintenanceWindowSchema = z
.object({
name: z
.string()
.min(1, "Name is required")
.max(100, "Name must be at most 100 characters"),
repeat: z.string(),
startDate: z.string().min(1, "Start date is required"),
startTime: z.string().min(1, "Start time is required"),
duration: z.number().int().min(1, "Duration must be at least 1"),
durationUnit: z.string(),
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
})
.refine(
(data) => {
const startDateTime = dayjs(data.startDate)
.set("hour", parseInt(data.startTime.split(":")[0], 10))
.set("minute", parseInt(data.startTime.split(":")[1], 10));
return startDateTime.isAfter(dayjs());
},
{
message: "Start date and time must be in the future",
path: ["startDate"],
}
);
const maintenanceWindowBaseSchema = z.object({
name: z
.string()
.min(1, "Name is required")
.max(100, "Name must be at most 100 characters"),
repeat: z.string(),
startDate: z.string().min(1, "Start date is required"),
startTime: z.string().min(1, "Start time is required"),
duration: z.number().int().min(1, "Duration must be at least 1"),
durationUnit: z.string(),
monitors: z.array(z.string()).min(1, "At least one monitor is required"),
});
export const maintenanceWindowSchema = maintenanceWindowBaseSchema.refine(
(data) => {
const startDateTime = dayjs(data.startDate)
.set("hour", parseInt(data.startTime.split(":")[0], 10))
.set("minute", parseInt(data.startTime.split(":")[1], 10));
return startDateTime.isAfter(dayjs());
},
{
message: "Start date and time must be in the future",
path: ["startDate"],
}
);
export const maintenanceWindowEditSchema = maintenanceWindowBaseSchema;
export type MaintenanceWindowFormData = z.infer<typeof maintenanceWindowSchema>;
+26
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { GeoContinents } from "@/Types/GeoCheck";
import { DnsRecordTypes, PageSpeedStrategies } from "@/Types/Monitor";
// URL schema with custom error message
const urlSchema = z.url({ message: "Please enter a valid URL" });
@@ -89,6 +90,7 @@ const grpcSchema = baseSchema.extend({
const pagespeedSchema = baseSchema.extend({
type: z.literal("pagespeed"),
url: urlSchema,
strategy: z.enum(PageSpeedStrategies),
});
// Hardware/Infrastructure monitor schema
@@ -122,6 +124,29 @@ const websocketSchema = baseSchema.extend({
ignoreTlsErrors: z.boolean(),
});
// Hostname (FQDN) — labels of 1-63 alphanumerics/hyphens separated by dots,
// optionally prefixed with `_` for service labels (e.g. _dmarc, _imaps._tcp).
// No scheme, port, path, or whitespace. Total length ≤ 253.
const hostnameRegex =
/^(?=.{1,253}$)([a-zA-Z0-9_](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/;
// DNS monitor schema
const dnsSchema = baseSchema.extend({
type: z.literal("dns"),
url: z
.string()
.min(1, "Domain is required")
.regex(hostnameRegex, "Enter a valid domain (e.g. www.example.com)"),
dnsServer: z
.string()
.min(1, "DNS server is required")
.refine(
(v) => z.ipv4().safeParse(v).success || z.ipv6().safeParse(v).success,
"Enter a valid IPv4 or IPv6 address (e.g. 8.8.8.8)"
),
dnsRecordType: z.enum(DnsRecordTypes),
});
// Discriminated union of all monitor types
export const monitorSchema = z.discriminatedUnion("type", [
httpSchema,
@@ -133,6 +158,7 @@ export const monitorSchema = z.discriminatedUnion("type", [
pagespeedSchema,
hardwareSchema,
websocketSchema,
dnsSchema,
]);
export type MonitorFormData = z.infer<typeof monitorSchema>;
File diff suppressed because it is too large. Load diff
+44 -2
View File
@@ -30,6 +30,7 @@
"home": "Home"
},
"buttons": {
"selected": "selected",
"addMember": "Add member",
"cancel": "Cancel",
"close": "Close",
@@ -425,6 +426,20 @@
},
"common": {
"monitors": {
"bulkEdit": {
"selectAll": "Select All",
"editButton": "Edit Notifications",
"title": "Edit Notifications",
"selectedText": "You are applying changes to {{count}} monitor(s).",
"actionAdd": "Add",
"actionAddDesc": "Adds the selected notifications to these monitors without removing existing ones.",
"actionRemove": "Remove",
"actionRemoveDesc": "Removes exclusively the selected notifications from these monitors.",
"actionSet": "Replace all",
"actionSetDesc": "Replaces all existing notifications. Leave empty to clear all notifications.",
"selectLabel": "Notification Channels",
"selectPlaceholder": "Select channels..."
},
"actions": {
"configure": "Configure",
"delete": "Delete",
@@ -475,7 +490,8 @@
"optionPagespeed": "PageSpeed",
"optionHardware": "Infrastructure",
"optionGrpc": "gRPC",
"optionWebSocket": "WebSocket"
"optionWebSocket": "WebSocket",
"optionDns": "DNS"
}
}
},
@@ -562,9 +578,29 @@
"label": "WebSocket URL",
"placeholder": "wss://example.com/socket"
},
"strategy": {
"label": "Strategy",
"desktop": "Desktop",
"mobile": "Mobile"
},
"captureUrl": {
"label": "Capture endpoint",
"placeholder": "http://192.168.1.10:5001/api/v1/metrics"
},
"dnsServer": {
"label": "DNS server",
"placeholder": "8.8.8.8"
},
"dnsRecordType": {
"label": "DNS record type",
"value": {
"A": "A",
"AAAA": "AAAA",
"CNAME": "CNAME",
"MX": "MX",
"NS": "NS",
"TXT": "TXT"
}
}
},
"title": "General settings",
@@ -577,7 +613,8 @@
"pagespeed": "Track page load performance, Core Web Vitals, and optimization scores for your website.",
"grpc": "Enter the hostname and port of the gRPC server, optionally specify a service name for the health check, and add a display name.",
"websocket": "Enter the WebSocket URL to monitor (e.g., wss://example.com/socket) and add a display name.",
"hardware": "Monitor CPU, memory, disk usage, and temperature for your infrastructure. The Capture endpoint URL must include the full path /api/v1/metrics (e.g. http://192.168.1.10:5001/api/v1/metrics). For the authorization secret, paste only the token string — don't include 'Bearer'."
"hardware": "Monitor CPU, memory, disk usage, and temperature for your infrastructure. The Capture endpoint URL must include the full path /api/v1/metrics (e.g. http://192.168.1.10:5001/api/v1/metrics). For the authorization secret, paste only the token string — don't include 'Bearer'.",
"dns": "Monitor if a specific DNS server is responding."
}
},
"ignoreTls": {
@@ -614,6 +651,7 @@
"optionHttpDescription": "Use HTTP(S) to monitor your website or API endpoint.",
"optionPingDescription": "Use ICMP Ping to monitor if a server is online.",
"optionPortDescription": "Monitor if a specific port on a server is open.",
"optionDnsDescription": "Monitor if a specific DNS server is responding.",
"title": "Type"
},
"thresholds": {
@@ -1084,6 +1122,10 @@
}
},
"pageSpeed": {
"strategy": {
"desktop": "Desktop",
"mobile": "Mobile"
},
"charts": {
"common": {
"cls": "Cumulative Layout Shift (CLS)",
+5
View File
@@ -40,6 +40,11 @@ RUN npm run build
COPY --from=frontend-build /app/client/dist ./public
RUN chown -R node:node ./public \
&& chown -R node:node ./dist \
&& chown -R node:node ./scripts
EXPOSE 52345
CMD ["sh", "-c", "./scripts/inject-vars.sh && node ./dist/index.js"]
+6 -2
View File
@@ -26,8 +26,12 @@ RUN cp -r src/templates dist/templates
COPY --from=frontend-build /app/client/dist ./public
RUN chmod +x ./scripts/inject-vars.sh
RUN chmod +x ./scripts/inject-vars.sh \
&& chown -R node:node ./public \
&& chown -R node:node ./dist \
&& chown -R node:node ./scripts
EXPOSE 52345
CMD ./scripts/inject-vars.sh && node ./dist/index.js
CMD ["sh", "-c", "./scripts/inject-vars.sh && node ./dist/index.js"]
+114
View File
@@ -0,0 +1,114 @@
# Checkmate API documentation
Public-facing API documentation that powers **https://checkmate.so/docs**.
The site is built with [Astro Starlight](https://starlight.astro.build/) — a static-site generator that produces a fast, modern docs site with zero JavaScript by default. Starlight is open source and self-hostable; there is no third-party account required to publish.
## Repository layout
```
docs/
├── api-content/ ← markdown prose (this folder — edit here)
│ ├── introduction.md
│ ├── quickstart.md
│ ├── authentication.md
│ ├── conventions.md
│ ├── errors.md
│ ├── rate-limiting.md
│ └── api-reference/
│ └── overview.md
└── api/ ← Astro Starlight project (build tool — leave alone unless changing the site)
├── package.json
├── astro.config.mjs
├── src/content.config.ts
└── src/styles/checkmate.css
```
**Contributors editing prose only need to touch `docs/api-content/`**. Astro's content loader picks up the markdown automatically.
The endpoint reference (every URL + schema) is **auto-generated from [`server/openapi.json`](../../server/openapi.json)** via the `starlight-openapi` plugin. Adding or changing an endpoint means updating that JSON; the public docs pick it up on the next Vercel build.
## Local preview
```bash
cd docs/api
npm install
npm run dev
```
Visit http://localhost:4321/docs. Hot-reload works for markdown changes in `docs/api-content/`.
To produce the static site:
```bash
npm run build # outputs docs/api/dist/
npm run preview # serve the built output locally
```
## Deploying to checkmate.so/docs
Astro Starlight builds a static site. Deploy on Vercel and reverse-proxy `checkmate.so/docs/*` to it.
### One-time Vercel setup
1. Go to https://vercel.com → New Project → import the `bluewave-labs/Checkmate` GitHub repo.
2. **Root Directory**: set to `docs/api`.
3. **Framework Preset**: Vercel auto-detects Astro from `vercel.json`.
4. **Build & Output**: leave defaults (`npm run build` → `dist/`).
5. **Production Branch**: `develop`.
6. Deploy. Vercel returns a URL like `checkmate-docs.vercel.app`.
7. Verify the site renders correctly.
The deployment auto-rebuilds on every push to `develop` and on every PR (as a preview deploy).
### Reverse-proxy /docs to Vercel
In whichever edge proxy fronts `checkmate.so`, route `/docs/*` to the Vercel deployment.
**Cloudflare Workers:**
```javascript
addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (url.pathname === "/docs" || url.pathname.startsWith("/docs/")) {
const target = new URL(url.pathname, "https://checkmate-docs.vercel.app");
target.search = url.search;
return event.respondWith(fetch(target.toString(), event.request));
}
});
```
**nginx:**
```nginx
location /docs/ {
proxy_pass https://checkmate-docs.vercel.app/docs/;
proxy_set_header Host checkmate-docs.vercel.app;
proxy_ssl_server_name on;
}
```
The `base: "/docs"` setting in `astro.config.mjs` ensures every internal link and asset URL is prefixed correctly so the site works at `checkmate.so/docs/...` rather than the root.
## Updating the docs
| Task | What to edit |
|---|---|
| Fix a typo, clarify wording | `docs/api-content/*.md` |
| Add a new narrative page | Add the file to `docs/api-content/`, then add a `slug` entry to `astro.config.mjs` → `sidebar` |
| Fix something in the API reference | Edit `server/openapi.json` (or the route spec it's built from) — never edit the generated reference pages |
| Change branding / colors | `docs/api/src/styles/checkmate.css` |
| Change site config (title, logo, social) | `docs/api/astro.config.mjs` |
Two rules:
1. **Never hand-edit the API reference.** It's regenerated on every build. Fix the spec.
2. **Test code samples against a real instance before merging.** Wrong code in docs is worse than missing code.
## Why Astro Starlight (and not Mintlify, Docusaurus, etc.)
- **No third-party account required.** Self-hostable on any static host.
- **Best looking** of the modern docs frameworks per multiple 2026 reviews — Distr, among others, migrated away from Docusaurus specifically for Starlight's design.
- **Zero JavaScript by default.** Pages are pure HTML — fast load, perfect Lighthouse scores.
- **OpenAPI integration is first-class** via `starlight-openapi`.
- **Markdown is the source of truth.** No proprietary formats. Easy to migrate later if needed.
@@ -0,0 +1,47 @@
---
title: API reference overview
description: All endpoints, grouped by resource. Auto-generated from the OpenAPI spec.
---
# API reference
The full machine-readable specification is at [`server/openapi.json`](https://github.com/bluewave-labs/Checkmate/blob/develop/server/openapi.json). Mintlify renders an interactive reference from it — each endpoint below is fully documented with request/response schemas, examples, and a built-in "Try it" form.
## Endpoint groups
| Group | Description |
|---|---|
| **auth** | Register, log in, password recovery, manage users |
| **invite** | Send and redeem team invites |
| **monitors** | Create, update, pause, and delete monitors |
| **checks** | Read individual check results and team-wide summaries |
| **incidents** | List, filter, and resolve downtime incidents |
| **maintenance-window** | Schedule maintenance windows to silence checks |
| **notifications** | Configure email, Slack, Discord, and webhook channels |
| **status-page** | Manage public status pages |
| **geo-checks** | Multi-region check results |
| **logs** | Audit and operational logs |
| **settings** | Global Checkmate settings |
| **queue** | Background-job queue health (operational) |
| **diagnostic** | System health and version info |
## Authentication
Every endpoint except the unauthenticated auth/recovery routes requires:
```
Authorization: Bearer <jwt>
```
See [Authentication](/api/authentication) for how to obtain a token.
## Conventions recap
- Base URL: `https://your-checkmate-host/api/v1`
- Response envelope: `{ success, msg, data }`
- IDs: 24-character MongoDB ObjectIds
- Timestamps: ISO 8601 UTC
- Durations: integers in milliseconds
- Most resources are team-scoped — pass `teamId` where the path includes `/team/...`
See [Conventions](/api/conventions) for full details.
+137
View File
@@ -0,0 +1,137 @@
---
title: Authentication
description: Obtain a JWT from /auth/login and send it as a Bearer token on every subsequent request.
---
# Authentication
Checkmate uses **JWT bearer tokens**. There are no API keys, no OAuth, and no client secrets. Every API user is a regular Checkmate user — the credentials you log in to the web UI with are the credentials you use to obtain a token.
## The flow
1. **Get a token** by calling `POST /auth/login` with your email and password.
2. **Send the token** as `Authorization: Bearer <token>` on every subsequent request.
3. **Refresh** by calling `POST /auth/login` again before the token expires.
## Obtaining a token
```bash
curl -X POST https://your-checkmate-host/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "you@example.com",
"password": "YourPass1!"
}'
```
A successful response returns the token plus the authenticated user record:
```json
{
"success": true,
"msg": "OK",
"data": {
"user": {
"_id": "65f1c2a4d8b9e0123456789a",
"firstName": "Ada",
"lastName": "Lovelace",
"email": "you@example.com",
"role": ["admin"],
"teamId": "65f1c2a4d8b9e01234567890",
"createdAt": "2026-04-01T10:00:00.000Z",
"updatedAt": "2026-04-15T14:30:00.000Z"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
```
Store both `token` (for the `Authorization` header) and `user.teamId` (most resource endpoints are scoped by team).
## Using a token
Every authenticated request must include:
```
Authorization: Bearer <token>
```
```bash
curl https://your-checkmate-host/api/v1/monitors/team/<teamId> \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
```javascript
const res = await fetch("https://your-checkmate-host/api/v1/monitors/team/<teamId>", {
headers: { Authorization: `Bearer ${token}` },
});
```
## Token lifetime
Tokens expire after the duration configured by the operator via the `TOKEN_TTL` environment variable. The default is **99 days**.
There is no separate refresh-token endpoint. When a token is close to expiry — or after a 401 response — call `POST /auth/login` again to obtain a new one.
## Roles
The `user.role` claim is an array. Available roles:
| Role | Capability |
|---|---|
| `superadmin` | Full access to all teams and global settings. Can promote other users. |
| `admin` | Full access within their team. |
| `user` | Read access within their team. |
| `demo` | Limited demo-mode access. |
A user can hold multiple roles simultaneously.
## Registering the first user
A fresh Checkmate instance has no users. The first call to `POST /auth/register` creates the first **superadmin** and provisions a team for them:
```bash
curl -X POST https://your-checkmate-host/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"firstName": "Ada",
"lastName": "Lovelace",
"email": "ada@example.com",
"password": "Hunter2!",
"role": ["superadmin"],
"teamId": ""
}'
```
After the first user exists, additional users are usually created via the invite flow rather than `POST /auth/register`:
```
POST /invite/send # superadmin/admin sends an invite
POST /auth/register # invitee redeems the invite token
```
You can check whether a superadmin already exists with:
```bash
curl https://your-checkmate-host/api/v1/auth/users/superadmin
```
```json
{ "success": true, "data": true }
```
## Password recovery
The password-recovery flow is three calls, all unauthenticated:
```
POST /auth/recovery/request # user requests a recovery email
POST /auth/recovery/validate # client validates the recovery token
POST /auth/recovery/reset # user sets a new password
```
## Logging out
JWTs are stateless — there is no server-side logout. Drop the token from your client storage. If you need to invalidate a token before its expiry (e.g. a compromised device), the operator must rotate the `JWT_SECRET` environment variable, which invalidates every outstanding token.
Next: [Conventions](/api/conventions).
+122
View File
@@ -0,0 +1,122 @@
---
title: Conventions
description: Response envelope, request format, identifiers, pagination, and team scoping.
---
# Conventions
A small number of conventions apply to every endpoint. Once you've internalized them, the per-resource reference is mostly self-explanatory.
## Request format
- **Content-Type**: `application/json` for all POST/PUT/PATCH bodies, except multipart uploads (logos, profile images), which use `multipart/form-data`.
- **Charset**: UTF-8.
- **Method semantics**:
- `GET` — read, never mutates state.
- `POST` — create, or action that doesn't fit GET/PATCH/DELETE.
- `PATCH` — partial update.
- `PUT` — full replace.
- `DELETE` — delete.
## Response envelope
Every JSON response uses the same shape:
```json
{
"success": true,
"msg": "OK",
"data": { /* endpoint-specific payload */ }
}
```
| Field | Type | Meaning |
|---|---|---|
| `success` | boolean | `true` on 2xx, `false` on 4xx/5xx |
| `msg` | string | Human-readable summary — safe to surface in UIs |
| `data` | object \| array \| null | Endpoint-specific payload. Absent or `null` for `204 No Content`. |
Error responses use the same envelope with `success: false` and `data` typically omitted. See [Errors](/api/errors).
## Identifiers
- All resource IDs are **MongoDB ObjectIds** (24-character hex strings):
```
65f1c2a4d8b9e0123456789a
```
- Treat IDs as opaque strings. Do not attempt to parse the timestamp or counter components.
## Team scoping
Most resources belong to a **team**. After login, the user record contains a `teamId`; pass it as a path parameter wherever the endpoint name includes `/team/...`:
```
GET /monitors/team/65f1c2a4d8b9e01234567890
GET /incidents/team
GET /checks/team
```
Users only see resources belonging to their own team, except for `superadmin`, who can read across teams.
## Date and time
- All timestamps in JSON are **ISO 8601** strings in UTC:
```
"createdAt": "2026-04-01T10:00:00.000Z"
```
- Durations are typically integers in **milliseconds** (intervals, response times, time windows).
## Pagination
Endpoints that return collections accept these optional query parameters:
| Parameter | Type | Default | Notes |
|---|---|---|---|
| `limit` | integer | endpoint-dependent | Maximum rows to return. |
| `page` | integer | `0` | Zero-indexed page number. |
| `sortBy` | string | endpoint-dependent | Field to sort by. |
| `sortOrder` | `asc` \| `desc` | `desc` | Sort direction. |
| `filter` | string | — | Endpoint-specific filter (e.g. status). |
When a collection supports pagination, the response `data` includes the rows plus the total count:
```json
{
"success": true,
"msg": "OK",
"data": {
"monitors": [ /* … */ ],
"filteredMonitors": [ /* … */ ],
"summary": { /* counters */ }
}
}
```
Exact shapes vary per endpoint. See the [API reference](/api/reference) for each endpoint's response schema.
## File uploads
Two endpoints accept files:
- Status page logo: `POST /status-page` (multipart, field `logo`)
- User profile picture: `POST /auth/register`, `PATCH /auth/user/:id` (multipart, field `profileImage`)
Use `multipart/form-data` and include the JSON fields as separate form parts.
## CORS
The server's CORS policy is configured via the `CLIENT_HOST` environment variable. Only requests whose `Origin` matches `CLIENT_HOST` are accepted, and credentials (cookies) are allowed.
If you're calling the API from a browser on a different origin, the operator must add that origin to `CLIENT_HOST`. Server-to-server calls (curl, your backend) are not subject to CORS.
## Versioning
The base path includes the API version:
```
/api/v1/...
```
Within `v1`, additive changes (new endpoints, new optional fields) ship without notice. Breaking changes (removed endpoints, changed field types) only ship under a new major version.
Next: [Errors](/api/errors).
+124
View File
@@ -0,0 +1,124 @@
---
title: Errors
description: HTTP status codes Checkmate returns, what they mean, and how to handle them.
---
# Errors
Failure responses share the same envelope as successful ones, with `success: false` and `data` omitted (or `null`):
```json
{
"success": false,
"msg": "Validation failed: email must be a valid email"
}
```
Always treat the **HTTP status code** as the source of truth for handling logic, and surface `msg` to humans.
## Status codes
| Status | Meaning | When you'll see it |
|---|---|---|
| `200 OK` | Request succeeded with a body | Most GETs, successful mutations that return the new resource |
| `204 No Content` | Request succeeded with no body | DELETEs, successful actions like `/status-page/:url/unlock` |
| `400 Bad Request` | Malformed request | Missing required path param, malformed JSON, invalid file upload |
| `401 Unauthorized` | Missing or invalid JWT | Token expired, token missing, token signed with a different secret |
| `403 Forbidden` | Authenticated, but not allowed | Accessing a resource that belongs to a different team, or insufficient role |
| `404 Not Found` | Resource doesn't exist | Wrong ID, deleted resource, mistyped path |
| `409 Conflict` | Operation would violate a constraint | Duplicate email on register, slug already taken on status page |
| `413 Payload Too Large` | File upload exceeded limit | Logo or profile image too big |
| `422 Unprocessable Entity` | Request was well-formed but failed validation | Zod / Joi schema rejected the body |
| `429 Too Many Requests` | Rate limit exceeded | See [Rate limiting](/api/rate-limiting) |
| `500 Internal Server Error` | Unexpected server error | A bug — report it with the request ID |
## Common shapes
### 401 — missing or invalid token
```json
{
"success": false,
"msg": "No auth token provided"
}
```
Re-authenticate by calling `POST /auth/login`.
### 422 — validation error
```json
{
"success": false,
"msg": "\"email\" must be a valid email"
}
```
The `msg` describes the first failing field. Re-send the request with the fix.
### 403 — forbidden
```json
{
"success": false,
"msg": "Forbidden"
}
```
You're authenticated but the resource isn't visible to you. Common cause: passing a `teamId` that isn't your team's.
### 429 — rate limited
```json
{
"success": false,
"msg": "Too many requests"
}
```
Inspect `RateLimit-*` response headers and back off. See [Rate limiting](/api/rate-limiting).
## Error handling pattern
Client code should branch on status code, not on `msg`:
```javascript
const res = await fetch(url, opts);
const body = await res.json().catch(() => ({}));
switch (res.status) {
case 200:
case 204:
return body.data;
case 401:
// Token expired or missing — re-authenticate, then retry once.
await reauthenticate();
return retry();
case 422:
// Surface the validation error to the user.
throw new ValidationError(body.msg);
case 429:
// Back off using Retry-After if present.
const retryAfter = Number(res.headers.get("Retry-After") ?? 60);
await sleep(retryAfter * 1000);
return retry();
default:
throw new Error(`Checkmate API ${res.status}: ${body.msg ?? res.statusText}`);
}
```
## Reporting bugs
If you see a `500`, capture:
- The exact request (method, path, body — **redact secrets**)
- The full response body and headers
- A timestamp in UTC
Open an issue at https://github.com/bluewave-labs/Checkmate/issues with that information.
Next: [Rate limiting](/api/rate-limiting).
+84
View File
@@ -0,0 +1,84 @@
---
title: Introduction
description: Use the Checkmate REST API to manage monitors, incidents, status pages, notifications, and users programmatically.
---
# Checkmate API
Checkmate exposes a REST API that mirrors everything the web UI can do. Use it to provision monitors from infrastructure-as-code, build internal dashboards, automate incident workflows, or integrate Checkmate into your existing alerting stack.
The web UI you log in to is itself just a client of this same API.
## Base URL
```
https://<your-checkmate-host>/api/v1
```
Replace `<your-checkmate-host>` with the domain where you deployed Checkmate. For local development:
```
http://localhost:52345/api/v1
```
All endpoints are relative to this base. Every path on this page is shown without the `/api/v1` prefix — prepend it when making requests.
## API stability
The API is at version **`v1`** and is considered stable. Breaking changes will only ship under a new major version (`/api/v2`).
## What you can do
| Resource | What it covers |
|---|---|
| `monitors` | Create, update, pause, and delete monitors of any type (HTTP, Ping, Port, DNS, Docker, PageSpeed, gRPC, WebSocket, Game, Hardware) |
| `checks` | Read individual check results and aggregated stats |
| `incidents` | List, filter, and resolve downtime incidents |
| `notifications` | Manage notification channels (email, Slack, Discord, webhooks) |
| `status-page` | Configure public status pages |
| `maintenance-window` | Schedule maintenance windows so checks don't fire incidents |
| `geo-checks` | Multi-region check results |
| `auth` | Register, log in, manage users |
| `invite` | Invite teammates |
| `logs` | Audit and operational logs |
| `settings` | Tune global Checkmate settings |
| `queue` | Inspect the background-job queue (operational) |
| `diagnostic` | Health and system info |
## What you'll need
1. A running Checkmate instance you administer.
2. A user account on that instance.
3. A JWT obtained by calling `POST /auth/login` — see [Authentication](/api/authentication).
There is no separate "API key" concept in Checkmate. The same JWT that authenticates the web UI authenticates every API call.
## Response shape
Every endpoint returns the same envelope:
```json
{
"success": true,
"msg": "OK",
"data": { /* endpoint-specific payload */ }
}
```
See [Conventions](/api/conventions) for the full contract and [Errors](/api/errors) for failure shapes.
## Quick example
```bash
# 1. Log in to get a token
TOKEN=$(curl -s -X POST https://your-checkmate-host/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"you@example.com","password":"YourPass1!"}' \
| jq -r '.data.token')
# 2. List your team's monitors
curl https://your-checkmate-host/api/v1/monitors/team/<teamId> \
-H "Authorization: Bearer $TOKEN"
```
Next: [Authentication](/api/authentication).
+117
View File
@@ -0,0 +1,117 @@
---
title: Quickstart
description: From zero to a working monitor in under five minutes.
---
# Quickstart
This walkthrough creates a Checkmate user, logs in, provisions an HTTP monitor, and reads its checks — all via the API.
It assumes you have a Checkmate instance running and reachable. Substitute `https://your-checkmate-host` with your actual host throughout.
## 1. Register the first user
If your instance is fresh, the first user becomes a superadmin:
```bash
curl -X POST https://your-checkmate-host/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"firstName": "Ada",
"lastName": "Lovelace",
"email": "ada@example.com",
"password": "Hunter2!Hunter2!",
"role": ["superadmin"],
"teamId": ""
}'
```
The response includes a JWT and a freshly-created `teamId`. Save both.
If a superadmin already exists, skip to step 2 and use existing credentials.
## 2. Log in
If you already have an account:
```bash
TOKEN=$(curl -s -X POST https://your-checkmate-host/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"Hunter2!Hunter2!"}' \
| jq -r '.data.token')
TEAM_ID=$(curl -s -X POST https://your-checkmate-host/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"ada@example.com","password":"Hunter2!Hunter2!"}' \
| jq -r '.data.user.teamId')
echo "Token: $TOKEN"
echo "Team: $TEAM_ID"
```
## 3. Create a monitor
This creates an HTTP monitor that probes example.com every 60 seconds:
```bash
curl -X POST https://your-checkmate-host/api/v1/monitors \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"name\": \"example.com\",
\"type\": \"http\",
\"url\": \"https://example.com\",
\"interval\": 60000,
\"teamId\": \"$TEAM_ID\",
\"isActive\": true
}"
```
A successful response returns the new monitor including its `_id`.
## 4. List your team's monitors
```bash
curl https://your-checkmate-host/api/v1/monitors/team/$TEAM_ID \
-H "Authorization: Bearer $TOKEN"
```
You should see the monitor you just created. Within a minute, the background worker will have run a few checks against it.
## 5. Read recent checks
Replace `<MONITOR_ID>` with the `_id` from step 3:
```bash
curl "https://your-checkmate-host/api/v1/checks/<MONITOR_ID>?limit=10" \
-H "Authorization: Bearer $TOKEN"
```
You'll see an array of check results — status code, response time, timestamp, region (if applicable).
## 6. Pause and delete the monitor
Pause:
```bash
curl -X PATCH https://your-checkmate-host/api/v1/monitors/<MONITOR_ID> \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"isActive": false}'
```
Delete:
```bash
curl -X DELETE https://your-checkmate-host/api/v1/monitors/<MONITOR_ID> \
-H "Authorization: Bearer $TOKEN"
```
## What's next
- **Set up notifications** — `POST /notifications` to wire email / Slack / Discord / webhook channels, then attach them to monitors.
- **Build a status page** — `POST /status-page` to publish your monitors publicly.
- **Schedule maintenance** — `POST /maintenance-window` to silence checks during planned downtime.
- **Browse the full API reference** — see every endpoint with request/response schemas.
See the [reference](/api/reference) for the complete list of endpoints.
+83
View File
@@ -0,0 +1,83 @@
---
title: Rate limiting
description: Per-IP request limits, headers, and how to back off.
---
# Rate limiting
Checkmate applies two per-IP rate limiters, both with a **60-second window**:
| Limiter | Applies to | Limit |
|---|---|---|
| General | All requests under `/api/v1/*` | **600 requests / 60 seconds** |
| Auth-sensitive | `/auth/login`, `/auth/register`, `/auth/recovery/*`, `/status-page/:url/unlock` | **15 requests / 60 seconds** |
The two limiters are **independent**. Auth-sensitive endpoints count against both buckets — you can hammer `/auth/login` 15 times in a minute before being rate-limited there, but a single client can never exceed 600 total requests per minute regardless of which endpoints are called.
## Headers
Every response includes the standard `RateLimit-*` headers so you can pace yourself proactively:
```
RateLimit-Limit: 600
RateLimit-Remaining: 587
RateLimit-Reset: 42
```
| Header | Meaning |
|---|---|
| `RateLimit-Limit` | The cap for the current window. |
| `RateLimit-Remaining` | Requests left before you hit `429`. |
| `RateLimit-Reset` | Seconds until the window resets. |
## When you exceed the limit
You receive `HTTP 429 Too Many Requests`:
```json
{
"success": false,
"msg": "Too many requests"
}
```
The response also includes `Retry-After`:
```
Retry-After: 42
```
Wait that many seconds before retrying. If `Retry-After` is missing, fall back to the `RateLimit-Reset` header.
## Recommended backoff
For one-off scripts, simple sleep-then-retry is fine:
```javascript
async function callWithRetry(url, opts, attempts = 3) {
for (let i = 0; i < attempts; i++) {
const res = await fetch(url, opts);
if (res.status !== 429) return res;
const retry = Number(res.headers.get("Retry-After") ?? 60);
await new Promise(r => setTimeout(r, retry * 1000));
}
throw new Error("Rate limit retry exhausted");
}
```
For higher-throughput integrations, watch `RateLimit-Remaining` and pace your sender to stay below the limit rather than waiting for `429`.
## Limits and proxies
Rate-limiting is per **client IP**, derived from the connection — or, when Checkmate is behind a reverse proxy with `trust proxy` configured, from the leftmost public IP in `X-Forwarded-For`.
If many of your clients share an egress IP (NAT, corporate proxy), they share the bucket. In that case, an operator should either:
- Increase the limits (server code change required), or
- Make sure each client connects from a distinct IP.
## Limits are not contractual
The numbers above reflect the current defaults. An operator can change them at any time (they're hardcoded in `server/src/middleware/rateLimiter.ts`). If you're building an integration that depends on a higher limit, coordinate with the operator first.
Next: [API reference](/api/reference) — auto-generated from the OpenAPI spec.
+21
View File
@@ -0,0 +1,21 @@
# Astro build
dist/
.astro/
# Sources copied in at build time by scripts/sync-sources.mjs.
# Edit /docs/api-content/ and /server/openapi.json instead.
src/vendored/
# Dependencies
node_modules/
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Env
.env
.env.production
.vercel
+83
View File
@@ -0,0 +1,83 @@
import { defineConfig } from "astro/config";
import starlight from "@astrojs/starlight";
import starlightOpenAPI, { openAPISidebarGroups } from "starlight-openapi";
// The OpenAPI spec is vendored from server/openapi.json by
// scripts/sync-sources.mjs (runs as predev/prebuild). We point at the
// vendored copy so the build is self-contained — Vercel only uploads
// the docs/api/ subtree, so paths outside this directory are not
// available at build time.
const OPENAPI_PATH = "./src/vendored/openapi.json";
export default defineConfig({
// The deployed site serves at the root of its Vercel domain. The
// reverse proxy that maps checkmate.so/docs/* → Vercel must strip
// the /docs/ prefix before forwarding (the Cloudflare Worker snippet
// in docs/api-content/README.md does this).
site: "https://checkmate.so",
integrations: [
starlight({
title: "Checkmate API",
description: "Use the Checkmate REST API to manage monitors, incidents, status pages, notifications, and users programmatically.",
// Prose markdown is loaded from /docs/api-content via the custom
// docsLoader in src/content.config.ts. Keeping content outside the
// Astro project tree means contributors can edit it without dealing
// with Astro / Starlight tooling.
logo: {
src: "./src/assets/logo.svg",
replacesTitle: true,
},
favicon: "/favicon.svg",
customCss: ["./src/styles/checkmate.css"],
social: {
github: "https://github.com/bluewave-labs/Checkmate",
},
// Inject a "Releases" link into the site header.
components: {
SocialIcons: "./src/components/HeaderLinks.astro",
},
sidebar: [
{
label: "Getting started",
items: [
{ label: "Introduction", slug: "" },
{ label: "Quickstart", slug: "quickstart" },
{ label: "Authentication", slug: "authentication" },
],
},
{
label: "Core concepts",
items: [
{ label: "Conventions", slug: "conventions" },
{ label: "Errors", slug: "errors" },
{ label: "Rate limiting", slug: "rate-limiting" },
],
},
{
label: "API reference",
items: [
{ label: "Overview", slug: "api-reference/overview" },
// The OpenAPI plugin appends every endpoint under this group.
...openAPISidebarGroups,
],
},
],
plugins: [
starlightOpenAPI([
{
base: "api-reference",
label: "REST API",
schema: OPENAPI_PATH,
},
]),
],
}),
],
});
+7983
View File
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "checkmate-docs-api",
"type": "module",
"version": "0.1.0",
"private": true,
"description": "Public API documentation for Checkmate. Built with Astro Starlight.",
"scripts": {
"prebuild": "node ./scripts/sync-sources.mjs",
"predev": "node ./scripts/sync-sources.mjs",
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/starlight": "^0.32.0",
"astro": "^5.0.0",
"sharp": "^0.33.5",
"starlight-openapi": "^0.13.0"
}
}
+55
View File
@@ -0,0 +1,55 @@
// Copies external sources into the Astro project tree so the build is
// self-contained. Required because Vercel's "Root Directory" setting
// only uploads the docs/api/ subtree, leaving sibling/parent paths
// (server/openapi.json, docs/api-content/) outside the build context.
//
// Run automatically by predev / prebuild via package.json. If the
// external paths exist, they win; otherwise we assume the files were
// already vendored (e.g. by a previous run) and continue.
import { existsSync, mkdirSync, cpSync, copyFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const PROJECT_ROOT = join(__dirname, "..");
const REPO_ROOT = join(PROJECT_ROOT, "..", "..");
const SOURCES = [
{
// Markdown prose (the public docs content).
from: join(REPO_ROOT, "docs", "api-content"),
to: join(PROJECT_ROOT, "src", "vendored", "api-content"),
kind: "dir",
},
{
// OpenAPI spec — read at build time by starlight-openapi.
from: join(REPO_ROOT, "server", "openapi.json"),
to: join(PROJECT_ROOT, "src", "vendored", "openapi.json"),
kind: "file",
},
];
let synced = 0;
for (const src of SOURCES) {
if (!existsSync(src.from)) {
if (existsSync(src.to)) {
console.log(`[sync-sources] ${src.from} not present; using existing vendored copy.`);
continue;
}
console.error(`[sync-sources] ERROR: source missing and no vendored copy: ${src.from}`);
process.exit(1);
}
mkdirSync(dirname(src.to), { recursive: true });
if (src.kind === "dir") {
cpSync(src.from, src.to, { recursive: true });
} else {
copyFileSync(src.from, src.to);
}
const stat = statSync(src.from);
console.log(`[sync-sources] ${src.from} → ${src.to} (${stat.isDirectory() ? "dir" : `${stat.size} bytes`})`);
synced++;
}
console.log(`[sync-sources] OK (${synced} sources copied)`);
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 32" fill="none">
<rect x="2" y="6" width="20" height="20" rx="4" fill="#13715B"/>
<path d="M7 16l3.5 3.5L17 12" stroke="white" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
<text x="30" y="22" font-family="-apple-system, BlinkMacSystemFont, 'Inter', sans-serif" font-size="18" font-weight="600" fill="currentColor">Checkmate</text>
</svg>

After

Width:  |  Height:  |  Size: 424 B

+29
View File
@@ -0,0 +1,29 @@
---
// Renders next to the search/theme controls in Starlight's header.
// Adds a "Releases" link plus delegates to the default SocialIcons.
import Default from "@astrojs/starlight/components/SocialIcons.astro";
---
<a class="header-link" href="/releases">Releases</a>
<Default><slot /></Default>
<style>
.header-link {
color: var(--sl-color-white);
font-size: var(--sl-text-sm);
font-weight: 500;
text-decoration: none;
padding: 0.4rem 0.75rem;
border-radius: 0.375rem;
transition: background-color 0.15s ease;
}
.header-link:hover {
background-color: var(--sl-color-gray-5);
}
:global([data-theme="light"]) .header-link {
color: var(--sl-color-gray-6);
}
:global([data-theme="light"]) .header-link:hover {
background-color: var(--sl-color-gray-1);
}
</style>
+139
View File
@@ -0,0 +1,139 @@
---
interface Props {
version: string;
date: string;
headline: string;
highlights: string[];
isLatest?: boolean;
}
const { version, date, headline, highlights, isLatest = false } = Astro.props;
const formattedDate = new Date(date).toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
});
---
<article class="release-card">
<aside class="release-meta">
<time datetime={date}>{formattedDate}</time>
<span class="release-version">
{version}
{isLatest && <span class="latest-badge">Latest</span>}
</span>
</aside>
<div class="release-content">
<h2 class="release-headline">{headline}</h2>
<ul class="release-highlights">
{highlights.map((item) => <li>{item}</li>)}
</ul>
</div>
</article>
<style>
.release-card {
display: grid;
grid-template-columns: 200px 1fr;
gap: 2.5rem;
padding: 2rem 0;
border-bottom: 1px solid var(--sl-color-gray-5);
align-items: flex-start;
}
.release-card:last-child {
border-bottom: none;
}
.release-meta {
display: flex;
flex-direction: column;
gap: 0.4rem;
position: sticky;
top: 6rem;
}
.release-meta time {
color: var(--sl-color-gray-3);
font-size: var(--sl-text-sm);
font-feature-settings: "tnum";
}
.release-version {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: var(--sl-color-white);
font-weight: 600;
font-size: var(--sl-text-base);
font-variant-numeric: tabular-nums;
}
.latest-badge {
background: var(--sl-color-accent);
color: var(--sl-color-white);
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
padding: 0.15rem 0.5rem;
border-radius: 0.25rem;
line-height: 1.2;
}
.release-content {
min-width: 0;
}
.release-headline {
margin: 0 0 1rem 0;
font-size: var(--sl-text-xl);
font-weight: 600;
color: var(--sl-color-white);
line-height: 1.3;
}
.release-highlights {
margin: 0;
padding-left: 1.25rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.release-highlights li {
color: var(--sl-color-gray-2);
line-height: 1.55;
font-size: var(--sl-text-base);
}
.release-highlights li::marker {
color: var(--sl-color-accent);
}
:global([data-theme="light"]) .release-card {
border-bottom-color: var(--sl-color-gray-2);
}
:global([data-theme="light"]) .release-version,
:global([data-theme="light"]) .release-headline {
color: var(--sl-color-gray-6);
}
:global([data-theme="light"]) .release-highlights li {
color: var(--sl-color-gray-5);
}
@media (max-width: 768px) {
.release-card {
grid-template-columns: 1fr;
gap: 0.75rem;
padding: 1.5rem 0;
}
.release-meta {
position: static;
flex-direction: row;
align-items: center;
gap: 1rem;
}
}
</style>
+26
View File
@@ -0,0 +1,26 @@
import { defineCollection } from "astro:content";
import { glob } from "astro/loaders";
import { docsSchema } from "@astrojs/starlight/schema";
// Load markdown from a sibling folder so prose lives outside the Astro
// project tree. Contributors edit /docs/api-content/*.md without touching
// the build tool.
//
// Starlight's built-in docsLoader is hardcoded to src/content/docs/, so we
// use Astro's plain glob loader with a custom base and apply Starlight's
// schema on top. The collection name must remain "docs" — Starlight looks
// it up by that exact name.
export const collections = {
docs: defineCollection({
loader: glob({
// Vendored from /docs/api-content/ by scripts/sync-sources.mjs.
// This indirection keeps the build self-contained for Vercel
// (whose Root Directory setting limits the upload to docs/api/).
base: "./src/vendored/api-content",
// README is contributor-facing docs (how to build the site),
// not part of the published content.
pattern: ["**/[^_]*.{md,mdx}", "!README.md"],
}),
schema: docsSchema(),
}),
};
+168
View File
@@ -0,0 +1,168 @@
// Source of truth for the Releases timeline. Newest first.
// Each entry should focus on user-facing features — leave routine
// bumps, lint fixes, and dependency updates out.
export interface Release {
version: string;
date: string; // ISO 8601 yyyy-mm-dd
headline: string;
highlights: string[];
}
export const releases: Release[] = [
{
version: "v3.7.1",
date: "2026-04-29",
headline: "Status page themes and a polished incidents page",
highlights: [
"Pick a theme for your public status page: Refined, Modern, Bold, or Editorial",
"Choose between light, dark, or auto theme modes",
"Polished incidents page with better filtering and grouping",
"New empty state for the infrastructure network view",
"Remove-monitors confirmation modal in settings",
],
},
{
version: "v3.6.1",
date: "2026-04-23",
headline: "Twilio SMS notifications and incident comments",
highlights: [
"Send incident alerts via SMS using Twilio",
"Resolve incidents with a comment so context is preserved",
"Login page no longer shows the register tip when registration is closed",
"Removed TimescaleDB dependency for a leaner deployment",
"New monitor-lifecycle documentation",
],
},
{
version: "v3.5.1",
date: "2026-03-06",
headline: "Uptime over WebSockets, Globalping ping, and team member removal",
highlights: [
"Real-time uptime updates over WebSockets — no more polling delays",
"Use Globalping as the engine for distributed ping monitors",
"Admins can remove team members from the team settings page",
"Fixed dark-mode background and several theme contrast issues",
],
},
{
version: "v3.5.0",
date: "2026-03-04",
headline: "SWR data layer and tightened validation",
highlights: [
"Global SWR-based data fetching for snappier navigation and automatic revalidation",
"Stricter server-side validation across all monitor types",
"Env-var validation surfaces misconfiguration at startup, not at first failure",
"Logs page improvements for easier debugging",
],
},
{
version: "v3.4.0",
date: "2026-02-20",
headline: "Settings refactor and status page access fixes",
highlights: [
"Settings UI rebuilt for clarity and consistency",
"Fixed access rules so unpublished status pages remain admin-only",
"Several caching fixes for fresher data after configuration changes",
],
},
{
version: "v3.3",
date: "2026-01-27",
headline: "PageSpeed v2 details and a faster uptime details page",
highlights: [
"Rebuilt PageSpeed details view with deeper Core Web Vitals breakdown",
"v2 uptime details page with denser charts and faster loading",
"Recent-checks endpoint redesigned for lower latency",
"PageSpeed tooltips clarify what each metric means",
],
},
{
version: "v3.2.0",
date: "2025-09-18",
headline: "Notification bodies and uptime % charts",
highlights: [
"Customise the body of email, Slack, Discord, and webhook notifications",
"Toggle between absolute uptime and uptime % on monitor charts",
"Sliding-window threshold evaluation for more stable status decisions",
"Skip-maintenance notifications no longer fire during maintenance windows",
],
},
{
version: "v3.1",
date: "2025-08-20",
headline: "N-of-M alert thresholds and PagerDuty",
highlights: [
"Alert only after N consecutive failures out of M checks — fewer flaky alerts",
"PagerDuty notification channel",
"Streamlined maintenance window creation flow",
"Network service refactor for more reliable cross-region checks",
],
},
{
version: "v2.3",
date: "2025-07-08",
headline: "Resolvable incidents and a cleaner incidents UI",
highlights: [
"Mark incidents as resolved from the UI with a single click",
"Redesigned incidents page with better grouping",
"Move the status-page delete action out of harm's way",
"Configurable behavior when no notifications are attached to a monitor",
],
},
{
version: "v2.2",
date: "2025-07-07",
headline: "Notification management and i18n polish",
highlights: [
"Delete notification channels with confirmation",
"Sorted translation keys for easier maintenance",
"Many small i18n fixes across pages",
],
},
{
version: "v2.1",
date: "2025-05-13",
headline: "Maintenance window improvements and form fixes",
highlights: [
"Settings update flow rebuilt",
"Fixed monitor resume / pause behavior",
"Better PageSpeed reliability",
"Infrastructure monitor filtering improvements",
"Conditional alert rendering during maintenance windows",
],
},
{
version: "v2.0",
date: "2024-12-04",
headline: "Major UI refresh and password security",
highlights: [
"Major frontend redesign with a refreshed theme",
"Improved password validation and error messages",
"Many fixes to incident detail views, colors, and responsiveness",
],
},
{
version: "v1.1.0",
date: "2024-10-11",
headline: "Maintenance windows and JWT-expiry handling",
highlights: [
"Schedule maintenance windows so checks don't fire false incidents",
"Auto-logout users when their JWT expires",
"Centralised backend error handling",
"Initial maintenance-page feature",
],
},
{
version: "v1.0",
date: "2024-09-23",
headline: "First public release",
highlights: [
"HTTP, ping, port, and PageSpeed monitors",
"Incident detection with email and Discord notifications",
"Public status pages",
"Team management with role-based access",
"Open source under the AGPL — self-host the entire stack",
],
},
];
+59
View File
@@ -0,0 +1,59 @@
---
import StarlightPage from "@astrojs/starlight/components/StarlightPage.astro";
import ReleaseCard from "../components/ReleaseCard.astro";
import { releases } from "../data/releases";
---
<StarlightPage
frontmatter={{
title: "Releases",
description: "What's new in Checkmate — every release with the most important features.",
template: "splash",
pagefind: false,
}}
>
<div class="releases-intro">
<p>
Every meaningful Checkmate release, newest first. For the
complete commit history, see the
<a href="https://github.com/bluewave-labs/Checkmate/releases" rel="noopener">GitHub releases page</a>.
</p>
</div>
<div class="releases-timeline">
{releases.map((release, index) => (
<ReleaseCard
version={release.version}
date={release.date}
headline={release.headline}
highlights={release.highlights}
isLatest={index === 0}
/>
))}
</div>
</StarlightPage>
<style>
.releases-intro {
max-width: 60ch;
margin: 0 0 2rem 0;
color: var(--sl-color-gray-3);
font-size: var(--sl-text-base);
line-height: 1.55;
}
.releases-intro a {
color: var(--sl-color-accent-high);
text-decoration: underline;
text-underline-offset: 2px;
}
.releases-timeline {
max-width: 56rem;
margin: 0;
}
:global([data-theme="light"]) .releases-intro {
color: var(--sl-color-gray-5);
}
</style>
+23
View File
@@ -0,0 +1,23 @@
/* Checkmate brand colors layered on top of Starlight defaults. */
:root {
--sl-color-accent-low: #0e5a48;
--sl-color-accent: #13715b;
--sl-color-accent-high: #1a8a6f;
--sl-color-white: #ffffff;
--sl-color-gray-1: #eef2f0;
--sl-color-gray-2: #c9d3cf;
--sl-color-gray-3: #95a39d;
--sl-color-gray-4: #5c6d66;
--sl-color-gray-5: #3a4844;
--sl-color-gray-6: #2a3531;
--sl-color-black: #1a201e;
}
/* Light mode tweaks so the green accent reads against white. */
:root[data-theme="light"] {
--sl-color-accent-low: #d0e4dc;
--sl-color-accent: #13715b;
--sl-color-accent-high: #0e5a48;
--sl-color-text-accent: #0e5a48;
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"buildCommand": "npm run build",
"outputDirectory": "dist",
"framework": "astro",
"installCommand": "npm install"
}
+57 -12
View File
@@ -346,7 +346,7 @@
},
"type": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "unknown"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"url": {
"type": "string"
@@ -436,6 +436,13 @@
"geoCheckInterval": {
"type": "number"
},
"dnsServer": {
"type": "string"
},
"dnsRecordType": {
"type": "string",
"enum": ["A", "AAAA", "CNAME", "MX", "TXT", "NS"]
},
"teamId": {
"type": "string"
},
@@ -2981,7 +2988,7 @@
{
"schema": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"required": false,
"name": "type",
@@ -3416,7 +3423,7 @@
{
"schema": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"required": false,
"name": "type",
@@ -4664,7 +4671,8 @@
"format": "date-time"
}
},
"required": ["monitors", "name", "duration", "durationUnit", "start", "end", "repeat"]
"required": ["monitors", "name", "duration", "durationUnit", "start", "end", "repeat"],
"additionalProperties": false
}
}
}
@@ -5208,7 +5216,8 @@
"type": "string",
"enum": ["seconds", "minutes", "hours", "days"]
}
}
},
"additionalProperties": false
}
}
}
@@ -5439,13 +5448,13 @@
"anyOf": [
{
"type": "string",
"enum": ["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
{
"type": "array",
"items": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
}
}
]
@@ -5648,13 +5657,13 @@
"anyOf": [
{
"type": "string",
"enum": ["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
{
"type": "array",
"items": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "docker", "hardware", "port", "game", "grpc", "websocket"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
}
}
]
@@ -6862,7 +6871,7 @@
},
"type": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "unknown"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"statusWindowSize": {
"type": "number",
@@ -6975,6 +6984,10 @@
],
"default": ""
},
"strategy": {
"type": "string",
"enum": ["desktop", "mobile"]
},
"selectedDisks": {
"type": "array",
"items": {
@@ -7009,6 +7022,14 @@
"geoCheckInterval": {
"type": "number",
"minimum": 300000
},
"dnsServer": {
"type": "string",
"minLength": 1
},
"dnsRecordType": {
"type": "string",
"enum": ["A", "AAAA", "CNAME", "MX", "TXT", "NS"]
}
},
"required": ["name", "type", "url"]
@@ -7496,7 +7517,7 @@
},
"type": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "unknown"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"ignoreTlsErrors": {
"type": "boolean",
@@ -7630,6 +7651,10 @@
],
"default": ""
},
"strategy": {
"type": "string",
"enum": ["desktop", "mobile"]
},
"group": {
"anyOf": [
{
@@ -7659,6 +7684,14 @@
"minimum": 300000,
"default": 300000
},
"dnsServer": {
"type": "string",
"minLength": 1
},
"dnsRecordType": {
"type": "string",
"enum": ["A", "AAAA", "CNAME", "MX", "TXT", "NS"]
},
"createdAt": {
"type": "string"
},
@@ -8034,7 +8067,7 @@
},
"type": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "unknown"]
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"url": {
"type": "string"
@@ -8153,6 +8186,10 @@
}
]
},
"strategy": {
"type": "string",
"enum": ["desktop", "mobile"]
},
"selectedDisks": {
"type": "array",
"items": {
@@ -8187,6 +8224,14 @@
"geoCheckInterval": {
"type": "number",
"minimum": 300000
},
"dnsServer": {
"type": "string",
"minLength": 1
},
"dnsRecordType": {
"type": "string",
"enum": ["A", "AAAA", "CNAME", "MX", "TXT", "NS"]
}
}
}
+67 -52
View File
@@ -21,7 +21,7 @@
"dockerode": "4.0.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-rate-limit": "8.3.2",
"express-rate-limit": "^8.5.1",
"gamedig": "5.2.0",
"got": "14.4.7",
"handlebars": "^4.7.8",
@@ -811,14 +811,15 @@
}
},
"node_modules/@aws-sdk/xml-builder": {
"version": "3.972.16",
"resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.16.tgz",
"integrity": "sha512-iu2pyvaqmeatIJLURLqx9D+4jKAdTH20ntzB6BFwjyN7V960r4jK32mx0Zf7YbtOYAbmbtQfDNuL60ONinyw7A==",
"version": "3.972.22",
"resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.22.tgz",
"integrity": "sha512-PMYKKtJd70IsSG0yHrdAbxBr+ZWBKLvzFZfD3/urxgf6hXVMzuU5M+3MJ5G67RpOmLBu1fAUN65SbWuKUCOlAA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.13.1",
"fast-xml-parser": "5.5.8",
"@nodable/entities": "2.1.0",
"@smithy/types": "^4.14.1",
"fast-xml-parser": "5.7.2",
"tslib": "^2.6.2"
},
"engines": {
@@ -865,7 +866,6 @@
"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.28.6",
"@babel/generator": "^7.28.6",
@@ -1485,7 +1485,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -1530,7 +1529,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -3193,6 +3191,19 @@
"@tybys/wasm-util": "^0.10.0"
}
},
"node_modules/@nodable/entities": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz",
"integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/nodable"
}
],
"license": "MIT"
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -3757,9 +3768,9 @@
}
},
"node_modules/@smithy/types": {
"version": "4.13.1",
"resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.13.1.tgz",
"integrity": "sha512-787F3yzE2UiJIQ+wYW1CVg2odHjmaWLGksnKQHUrK/lYZSEcy1msuLVvxaR/sI2/aDe9U+TBuLsXnr3vod1g0g==",
"version": "4.14.1",
"resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.14.1.tgz",
"integrity": "sha512-59b5HtSVrVR/eYNei3BUj3DCPKD/G7EtDDe7OEJE7i7FtQFugYo6MxbotS8mVJkLNVf8gYaAlEBwwtJ9HzhWSg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
@@ -4244,7 +4255,6 @@
"integrity": "sha512-wGA0NX93b19/dZC1J18tKWVIYWyyF2ZjT9vin/NRu0qzzvfVzWjs04iq2rQ3H65vCTQYlRqs3YHfY7zjdV+9Kw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^5.0.0",
@@ -4405,7 +4415,6 @@
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.1.tgz",
"integrity": "sha512-QoiaXANRkSXK6p0Duvt56W208du4P9Uye9hWLWgGMDTEoKPhuenzNcC4vGUmrNkiOKTlIrBoyNQYNpSwfEZXSg==",
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -4643,7 +4652,6 @@
"integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.56.1",
"@typescript-eslint/types": "8.56.1",
@@ -5257,7 +5265,6 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -5836,7 +5843,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6730,7 +6736,6 @@
"resolved": "https://registry.npmjs.org/cssnano/-/cssnano-7.1.1.tgz",
"integrity": "sha512-fm4D8ti0dQmFPeF8DXSAA//btEmqCOgAc/9Oa3C1LW94h5usNrJEfrON7b4FkPZgnDEn6OUs5NdxiJZmAtGOpQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"cssnano-preset-default": "^7.0.9",
"lilconfig": "^3.1.3"
@@ -7495,7 +7500,6 @@
"integrity": "sha512-t5aPOpmtJcZcz5UJyY2GbvpDlsK5E8JqRqoKtfiKE3cNh437KIqfJr3A3AKf5k64NPx6d0G3dno6XDY05PqPtw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -7857,7 +7861,6 @@
"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
"integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
@@ -7900,12 +7903,12 @@
}
},
"node_modules/express-rate-limit": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.2.tgz",
"integrity": "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==",
"version": "8.5.1",
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.1.tgz",
"integrity": "sha512-5O6KYmyJEpuPJV5hNTXKbAHWRqrzyu+OI3vUnSd2kXFubIVpG7ezpgxQy76Zo5GQZtrQBg86hF+CM/NX+cioiQ==",
"license": "MIT",
"dependencies": {
"ip-address": "10.1.0"
"ip-address": "^10.2.0"
},
"engines": {
"node": ">= 16"
@@ -7990,9 +7993,9 @@
"license": "MIT"
},
"node_modules/fast-xml-builder": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.1.4.tgz",
"integrity": "sha512-f2jhpN4Eccy0/Uz9csxh3Nu6q4ErKxf0XIsasomfOihuSUa3/xw6w8dnOtCDgEItQFJG8KyXPzQXzcODDrrbOg==",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz",
"integrity": "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==",
"dev": true,
"funding": [
{
@@ -8002,13 +8005,14 @@
],
"license": "MIT",
"dependencies": {
"path-expression-matcher": "^1.1.3"
"path-expression-matcher": "^1.5.0",
"xml-naming": "^0.1.0"
}
},
"node_modules/fast-xml-parser": {
"version": "5.5.8",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.5.8.tgz",
"integrity": "sha512-Z7Fh2nVQSb2d+poDViM063ix2ZGt9jmY1nWhPfHBOK2Hgnb/OW3P4Et3P/81SEej0J7QbWtJqxO05h8QYfK7LQ==",
"version": "5.7.2",
"resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.2.tgz",
"integrity": "sha512-P7oW7tLbYnhOLQk/Gv7cZgzgMPP/XN03K02/Jy6Y/NHzyIAIpxuZIM/YqAkfiXFPxA2CTm7NtCijK9EDu09u2w==",
"dev": true,
"funding": [
{
@@ -8018,9 +8022,10 @@
],
"license": "MIT",
"dependencies": {
"fast-xml-builder": "^1.1.4",
"path-expression-matcher": "^1.2.0",
"strnum": "^2.2.0"
"@nodable/entities": "^2.1.0",
"fast-xml-builder": "^1.1.5",
"path-expression-matcher": "^1.5.0",
"strnum": "^2.2.3"
},
"bin": {
"fxparser": "src/cli/cli.js"
@@ -9097,9 +9102,9 @@
}
},
"node_modules/ip-address": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
"integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"license": "MIT",
"engines": {
"node": ">= 12"
@@ -9526,7 +9531,6 @@
"integrity": "sha512-F26gjC0yWN8uAA5m5Ss8ZQf5nDHWGlN/xWZIh8S5SRbsEKBovwZhxGd6LJlbZYxBgCYOtreSUyb8hpXyGC5O4A==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@jest/core": "30.2.0",
"@jest/types": "30.2.0",
@@ -11543,9 +11547,9 @@
}
},
"node_modules/mongoose": {
"version": "8.19.2",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.19.2.tgz",
"integrity": "sha512-ww2T4dBV+suCbOfG5YPwj9pLCfUVyj8FEA1D3Ux1HHqutpLxGyOYEPU06iPRBW4cKr3PJfOSYsIpHWPTkz5zig==",
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/mongoose/-/mongoose-8.23.1.tgz",
"integrity": "sha512-gHSPD8qEwRmiXapK17hEnFWZdcFENMegHTcw5XIIg2+7R8eXQvdwSiMpD/A2oG8tKzFLLHyRXd8/eaDPAVwZgQ==",
"license": "MIT",
"dependencies": {
"bson": "^6.10.4",
@@ -12154,9 +12158,9 @@
}
},
"node_modules/path-expression-matcher": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.2.1.tgz",
"integrity": "sha512-d7gQQmLvAKXKXE2GeP9apIGbMYKz88zWdsn/BN2HRWVQsDFdUY36WSLTY0Jvd4HWi7Fb30gQ62oAOzdgJA6fZw==",
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",
"integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==",
"dev": true,
"funding": [
{
@@ -12371,7 +12375,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -14210,9 +14213,9 @@
}
},
"node_modules/strnum": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.2.tgz",
"integrity": "sha512-DnR90I+jtXNSTXWdwrEy9FakW7UX+qUZg28gj5fk2vxxl7uS/3bpI4fjFYVmdK9etptYBPNkpahuQnEwhwECqA==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz",
"integrity": "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==",
"dev": true,
"funding": [
{
@@ -14394,7 +14397,6 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14563,7 +14565,6 @@
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
@@ -14727,7 +14728,6 @@
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15390,6 +15390,22 @@
"node": ">=18"
}
},
"node_modules/xml-naming": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz",
"integrity": "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/NaturalIntelligence"
}
],
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/xmlbuilder": {
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-8.2.2.tgz",
@@ -15562,7 +15578,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+1 -1
View File
@@ -41,7 +41,7 @@
"dockerode": "4.0.6",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"express-rate-limit": "8.3.2",
"express-rate-limit": "^8.5.1",
"gamedig": "5.2.0",
"got": "14.4.7",
"handlebars": "^4.7.8",
@@ -0,0 +1,111 @@
import mongoose from "mongoose";
import type { AnyBulkWriteOperation, Document } from "mongodb";
import { logger } from "@/utils/logger.js";
import MaintenanceWindowModel from "../models/MaintenanceWindow.js";
type GroupResult = {
_id: {
teamId: mongoose.Types.ObjectId;
name: string;
start: Date;
end: Date;
repeat: number;
durationUnit: string;
duration: number;
active: boolean;
};
docIds: mongoose.Types.ObjectId[];
monitorIds: mongoose.Types.ObjectId[];
};
export async function migrateMaintenanceWindowMonitorIdToArray(): Promise<void> {
const SERVICE_NAME = "Migration:MigrateMaintenanceWindowMonitorIdToArray";
try {
logger.info({
service: SERVICE_NAME,
message: "Starting migration of MaintenanceWindow.monitorId to monitorIds array (eager merge)",
});
const db = mongoose.connection.db;
if (!db) {
throw new Error("Database connection is not initialized");
}
// Group old-style docs by their scheduling key.
// Skip rows that already have a monitorIds array — those are either already migrated
// or in a partially-migrated state that needs manual review.
const groups: GroupResult[] = await MaintenanceWindowModel.aggregate<GroupResult>([
{
$match: {
monitorId: { $exists: true, $ne: null },
monitorIds: { $exists: false },
},
},
{
$group: {
_id: {
teamId: "$teamId",
name: "$name",
start: "$start",
end: "$end",
repeat: "$repeat",
durationUnit: "$durationUnit",
duration: "$duration",
active: "$active",
},
docIds: { $push: "$_id" },
monitorIds: { $addToSet: "$monitorId" },
},
},
]);
if (groups.length === 0) {
logger.info({ service: SERVICE_NAME, message: "No MaintenanceWindow documents needed migration" });
return;
}
const bulkOps: AnyBulkWriteOperation<Document>[] = [];
let originalDocCount = 0;
for (const group of groups) {
const { docIds, monitorIds } = group;
originalDocCount += docIds.length;
const [survivorId, ...duplicateIds] = docIds;
bulkOps.push({
updateOne: {
filter: { _id: survivorId },
update: {
$set: { monitorIds },
$unset: { monitorId: "" },
},
},
});
if (duplicateIds.length > 0) {
bulkOps.push({
deleteMany: {
filter: { _id: { $in: duplicateIds } },
},
});
}
}
const result = await MaintenanceWindowModel.collection.bulkWrite(bulkOps, { ordered: true });
const deletedCount = originalDocCount - groups.length;
logger.info({
service: SERVICE_NAME,
message: `Migration complete. Consolidated ${originalDocCount} old document(s) into ${groups.length} group window(s); deleted ${deletedCount} duplicate(s).`,
});
logger.debug({
service: SERVICE_NAME,
message: `bulkWrite result: modified=${result.modifiedCount}, deleted=${result.deletedCount}`,
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.error({ service: SERVICE_NAME, message: `Error during MaintenanceWindow migration: ${errorMessage}` });
throw error;
}
}
+2
View File
@@ -5,6 +5,7 @@ import { fixInfrastructureThresholds } from "./0004_fixInfrastructureThresholds.
import MigrationModel from "../models/Migration.js";
import { migrateStatusPageTypeToArray } from "./0005_migrateStatusPageTypeToArray.js";
import { cleanupDuplicateMonitorStatsForUniqueIndex } from "./0006_cleanupDuplicateMonitorStatsForUniqueIndex.js";
import { migrateMaintenanceWindowMonitorIdToArray } from "./0007_migrateMaintenanceWindowMonitorIdToArray.js";
import type { ILogger } from "@/utils/logger.js";
type MigrationEntry = {
@@ -19,6 +20,7 @@ const migrations: MigrationEntry[] = [
{ name: "0004_fixInfrastructureThresholds", execute: fixInfrastructureThresholds },
{ name: "0005_migrateStatusPageTypeToArray", execute: migrateStatusPageTypeToArray },
{ name: "0006_cleanupDuplicateMonitorStatsForUniqueIndex", execute: cleanupDuplicateMonitorStatsForUniqueIndex },
{ name: "0007_migrateMaintenanceWindowMonitorIdToArray", execute: migrateMaintenanceWindowMonitorIdToArray },
];
const runMigrations = async (logger?: ILogger) => {
+5 -5
View File
@@ -1,8 +1,8 @@
import { Schema, model, type Types } from "mongoose";
import { DurationUnits, type MaintenanceWindow } from "@/types/maintenanceWindow.js";
type MaintenanceWindowDocumentBase = Omit<MaintenanceWindow, "id" | "monitorId" | "teamId" | "start" | "end" | "createdAt" | "updatedAt"> & {
monitorId: Types.ObjectId;
type MaintenanceWindowDocumentBase = Omit<MaintenanceWindow, "id" | "monitorIds" | "teamId" | "start" | "end" | "createdAt" | "updatedAt"> & {
monitorIds: Types.ObjectId[];
teamId: Types.ObjectId;
start: Date;
end: Date;
@@ -17,10 +17,10 @@ interface MaintenanceWindowDocument extends MaintenanceWindowDocumentBase {
const MaintenanceWindowSchema = new Schema<MaintenanceWindowDocument>(
{
monitorId: {
type: Schema.Types.ObjectId,
monitorIds: {
type: [Schema.Types.ObjectId],
ref: "Monitor",
immutable: true,
index: true,
},
teamId: {
type: Schema.Types.ObjectId,
+5 -1
View File
@@ -1,6 +1,6 @@
import { Schema, model, Types } from "mongoose";
import type { Monitor, MonitorMatchMethod, CheckSnapshot } from "@/types/monitor.js";
import { DnsRecordTypes, MonitorTypes, MonitorStatuses } from "@/types/monitor.js";
import { DnsRecordTypes, MonitorTypes, MonitorStatuses, PageSpeedStrategies } from "@/types/monitor.js";
import type {
CheckAudits,
CheckCaptureInfo,
@@ -330,6 +330,10 @@ const MonitorSchema = new Schema<MonitorDocument>(
type: String,
default: "",
},
strategy: {
type: String,
enum: PageSpeedStrategies,
},
group: {
type: String,
trim: true,
@@ -29,7 +29,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
private toEntity = (doc: MaintenanceWindowDocument): MaintenanceWindow => {
return {
id: this.toStringId(doc._id),
monitorId: this.toStringId(doc.monitorId),
monitorIds: doc.monitorIds.map(this.toStringId),
teamId: this.toStringId(doc.teamId),
active: doc.active,
name: doc.name,
@@ -67,7 +67,7 @@ class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository
findByMonitorId = async (monitorId: string, teamId: string): Promise<MaintenanceWindow[]> => {
const maintenanceWindows = await MaintenanceWindowModel.find({
monitorId: monitorId,
monitorIds: monitorId,
teamId: teamId,
});
return this.mapDocuments(maintenanceWindows);
@@ -108,7 +108,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
$lookup: {
from: "maintenancewindows",
let: { monitorId: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$monitorId", "$$monitorId"] } } }],
pipeline: [{ $match: { $expr: { $in: ["$$monitorId", { $ifNull: ["$monitorIds", []] }] } } }],
as: "maintenanceWindows",
},
},
@@ -441,6 +441,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
selectedDisks: doc.selectedDisks ?? [],
gameId: doc.gameId ?? undefined,
grpcServiceName: doc.grpcServiceName ?? undefined,
strategy: doc.strategy ?? undefined,
group: doc.group ?? null,
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
geoCheckEnabled: doc.geoCheckEnabled ?? false,
@@ -502,6 +503,7 @@ class MongoMonitorsRepository implements IMonitorsRepository {
selectedDisks: doc.selectedDisks ?? [],
gameId: doc.gameId ?? undefined,
grpcServiceName: doc.grpcServiceName ?? undefined,
strategy: doc.strategy ?? undefined,
group: doc.group ?? null,
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
geoCheckEnabled: doc.geoCheckEnabled ?? false,
@@ -27,7 +27,11 @@ export interface IMaintenanceWindowService {
}): Promise<{ maintenanceWindows: MaintenanceWindow[]; maintenanceWindowCount: number }>;
getMaintenanceWindowsByMonitorId(params: { monitorId: string; teamId: string }): Promise<MaintenanceWindow[]>;
deleteMaintenanceWindow(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
editMaintenanceWindow(params: { id: string; teamId: string; body: Partial<MaintenanceWindow> }): Promise<MaintenanceWindow>;
editMaintenanceWindow(params: {
id: string;
teamId: string;
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
}): Promise<MaintenanceWindow>;
}
export class MaintenanceWindowService implements IMaintenanceWindowService {
@@ -84,20 +88,17 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
});
}
const dbTransactions = monitorIDs.map((monitorId: string) => {
return this.maintenanceWindowsRepository.create({
teamId,
monitorId,
name: name,
active: active,
duration: duration,
durationUnit: durationUnit,
repeat: repeat,
start: start,
end: end,
});
await this.maintenanceWindowsRepository.create({
teamId,
monitorIds: monitorIDs,
name: name,
active: active,
duration: duration,
durationUnit: durationUnit,
repeat: repeat,
start: start,
end: end,
});
await Promise.all(dbTransactions);
};
getMaintenanceWindowById = async ({ id, teamId }: { id: string; teamId: string }) => {
@@ -135,7 +136,32 @@ export class MaintenanceWindowService implements IMaintenanceWindowService {
return await this.maintenanceWindowsRepository.deleteById(id, teamId);
};
editMaintenanceWindow = async ({ id, teamId, body }: { id: string; teamId: string; body: Partial<MaintenanceWindow> }) => {
return await this.maintenanceWindowsRepository.updateById(id, teamId, body);
editMaintenanceWindow = async ({
id,
teamId,
body,
}: {
id: string;
teamId: string;
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
}) => {
const { monitors, ...rest } = body;
const update: Partial<MaintenanceWindow> = rest;
if (monitors !== undefined) {
const monitorDocs = await this.monitorsRepository.findByIds(monitors);
const unauthorizedMonitors = monitorDocs.filter((monitor) => monitor.teamId !== teamId);
if (unauthorizedMonitors.length > 0) {
throw new AppError({
message: "Unauthorized to edit maintenance window for one or more monitors",
service: SERVICE_NAME,
method: "editMaintenanceWindow",
status: 403,
});
}
update.monitorIds = monitors;
}
return await this.maintenanceWindowsRepository.updateById(id, teamId, update);
};
}
+6 -10
View File
@@ -9,7 +9,8 @@ import type {
GamesMap,
GroupedGeoCheckResult,
} from "@/types/monitor.js";
import { supportsGeoCheck } from "@/types/monitor.js";
import { supportsGeoCheck, supportsUptimeDetails } from "@/types/monitor.js";
import type { UptimeChecksResult, HardwareChecksResult, PageSpeedChecksResult } from "@/types/check.js";
import type { GeoContinent } from "@/types/geoCheck.js";
import type {
IChecksRepository,
@@ -28,6 +29,9 @@ import { ILogger } from "@/utils/logger.js";
const SERVICE_NAME = "MonitorService";
type DateRangeKey = "recent" | "day" | "week" | "month" | "all";
const isUptimeChecksResult = (result: UptimeChecksResult | HardwareChecksResult | PageSpeedChecksResult): result is UptimeChecksResult =>
supportsUptimeDetails(result.monitorType);
export interface IMonitorService {
readonly serviceName: string;
@@ -216,15 +220,7 @@ export class MonitorService implements IMonitorService {
});
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
if (
checksData.monitorType !== "http" &&
checksData.monitorType !== "ping" &&
checksData.monitorType !== "docker" &&
checksData.monitorType !== "port" &&
checksData.monitorType !== "game" &&
checksData.monitorType !== "grpc" &&
checksData.monitorType !== "websocket"
) {
if (!isUptimeChecksResult(checksData)) {
throw new AppError({ message: `${monitor.type} monitors are not supported for uptime details`, status: 400 });
}
@@ -16,11 +16,19 @@ export class DNSProvider implements IStatusProvider<DNSStatusPayload> {
async handle(monitor: Monitor): Promise<MonitorStatusResponse<DNSStatusPayload>> {
try {
const { url: hostname, dnsServer, dnsRecordType = "A" } = monitor;
const { url, dnsServer, dnsRecordType = "A" } = monitor;
if (!dnsServer) {
throw new Error("DNS server is required for DNS monitoring");
}
let hostname: string;
try {
const withScheme = /^[a-z]+:\/\//i.test(url) ? url : `http://${url}`; // Ensure URL has a scheme for proper parsing
hostname = new URL(withScheme).hostname;
} catch {
hostname = url;
}
const resolver = this.createResolver();
resolver.setServers([dnsServer]);
@@ -1,6 +1,6 @@
import { IStatusProvider } from "@/service/infrastructure/network/IStatusProvider.js";
import { MonitorStatusResponse, PageSpeedStatusPayload } from "@/types/network.js";
import { Monitor, MonitorType } from "@/types/monitor.js";
import { Monitor, MonitorType, DefaultPageSpeedStrategy } from "@/types/monitor.js";
import { HttpProvider } from "@/service/infrastructure/network/HttpProvider.js";
import { ISettingsService } from "@/service/system/settingsService.js";
import { ILogger } from "@/utils/logger.js";
@@ -19,14 +19,15 @@ export class PageSpeedProvider implements IStatusProvider<PageSpeedStatusPayload
}
async handle(monitor: Monitor): Promise<MonitorStatusResponse<PageSpeedStatusPayload>> {
const { url } = monitor;
const { url, strategy } = monitor;
try {
if (!url) throw new Error("URL is required for PageSpeed monitor");
const dbSettings = await this.settingsService.getDBSettings();
const apiKey = dbSettings?.pagespeedApiKey;
const resolvedStrategy = strategy ?? DefaultPageSpeedStrategy;
let pageSpeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(
url
)}&category=seo&category=accessibility&category=best-practices&category=performance`;
)}&strategy=${encodeURIComponent(resolvedStrategy)}&category=seo&category=accessibility&category=best-practices&category=performance`;
if (apiKey) {
pageSpeedUrl += `&key=${apiKey}`;
+1 -1
View File
@@ -3,7 +3,7 @@ export type DurationUnit = (typeof DurationUnits)[number];
export interface MaintenanceWindow {
id: string;
monitorId: string;
monitorIds: string[];
teamId: string;
active: boolean;
name: string;
+18
View File
@@ -6,9 +6,26 @@ export type { GeoContinent } from "@/types/geoCheck.js";
export const MonitorTypes = ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"] as const;
export type MonitorType = (typeof MonitorTypes)[number];
export const PageSpeedStrategies = ["desktop", "mobile"] as const;
export type PageSpeedStrategy = (typeof PageSpeedStrategies)[number];
export const DefaultPageSpeedStrategy: PageSpeedStrategy = "desktop";
export const GeoCheckSupportedTypes: readonly MonitorType[] = ["http", "ping"] as const;
export const supportsGeoCheck = (type: MonitorType): boolean => GeoCheckSupportedTypes.includes(type);
export const UptimeDetailsSupportedTypes = [
"http",
"ping",
"docker",
"port",
"game",
"grpc",
"websocket",
"dns",
] as const satisfies readonly MonitorType[];
export type UptimeDetailsSupportedType = (typeof UptimeDetailsSupportedTypes)[number];
export const supportsUptimeDetails = (type: MonitorType): type is UptimeDetailsSupportedType => UptimeDetailsSupportedTypes.some((t) => t === type);
export const MonitorStatuses = ["up", "down", "paused", "initializing", "maintenance", "breached"] as const;
export type MonitorStatus = (typeof MonitorStatuses)[number];
@@ -54,6 +71,7 @@ export interface Monitor {
selectedDisks: string[];
gameId?: string;
grpcServiceName?: string;
strategy?: PageSpeedStrategy;
group: string | null;
geoCheckEnabled?: boolean;
geoCheckLocations?: GeoContinent[];
+2 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { booleanCoercion } from "./shared.js";
import { GeoContinents } from "@/types/geoCheck.js";
import { MonitorTypes } from "@/types/monitor.js";
//****************************************
// Check Validations
@@ -11,7 +12,7 @@ export const getChecksParamValidation = z.object({
});
export const getChecksQueryValidation = z.object({
type: z.enum(["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket"]).optional(),
type: z.enum(MonitorTypes).optional(),
sortOrder: z.enum(["asc", "desc"]),
limit: z.coerce.number().optional(),
dateRange: z.enum(["recent", "hour", "day", "week", "month", "all"]),
@@ -72,7 +72,7 @@ export const editMaintenanceByIdWindowBodyValidation = z
start: dateToString.optional(),
end: dateToString.optional(),
expiry: dateToString.optional(),
monitors: z.array(z.string()).optional(),
monitors: z.array(z.string()).min(1, "At least one monitor is required").optional(),
duration: z.number().optional(),
durationUnit: z.enum(DurationUnits).optional(),
})
+139 -107
View File
@@ -1,7 +1,7 @@
import { z } from "zod";
import { booleanCoercion } from "./shared.js";
import { booleanCoercion, dnsHostnameRegex, dnsServerValidation } from "./shared.js";
import { GeoContinents } from "@/types/geoCheck.js";
import { DnsRecordTypes, MonitorMatchMethods, MonitorStatuses, MonitorTypes } from "@/types/monitor.js";
import { DnsRecordTypes, MonitorMatchMethods, MonitorStatuses, MonitorTypes, PageSpeedStrategies } from "@/types/monitor.js";
export const getMonitorByIdParamValidation = z.object({
monitorId: z.string().min(1, "Monitor ID is required"),
@@ -39,69 +39,97 @@ export const getCertificateParamValidation = z.object({
monitorId: z.string().min(1, "Monitor ID is required"),
});
export const createMonitorBodyValidation = z.object({
_id: z.string().optional(),
name: z.string().min(1, "Name is required"),
description: z.union([z.string(), z.literal("")]).optional(),
type: z.enum(MonitorTypes, "Invalid monitor type"),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
url: z.string().min(1, "URL is required"),
ignoreTlsErrors: z.boolean().default(false),
useAdvancedMatching: z.boolean().default(false),
port: z.number().optional(),
isActive: z.boolean().optional(),
interval: z.number().optional(),
cpuAlertThreshold: z.number().optional(),
memoryAlertThreshold: z.number().optional(),
diskAlertThreshold: z.number().optional(),
tempAlertThreshold: z.number().optional(),
notifications: z.array(z.string()).optional(),
secret: z.string().optional(),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
selectedDisks: z.array(z.string()).optional(),
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
geoCheckEnabled: z.boolean().optional(),
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
geoCheckInterval: z.number().min(300000).optional(),
dnsServer: z.string().optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
});
const refineDnsHostname = (body: { type?: string; url?: string }, ctx: z.RefinementCtx) => {
if (body.type === "dns" && body.url && !dnsHostnameRegex.test(body.url)) {
ctx.addIssue({
code: "custom",
path: ["url"],
message: "Enter a valid domain (e.g. www.example.com)",
});
}
};
export const editMonitorBodyValidation = z.object({
name: z.string().optional(),
type: z.enum(MonitorTypes).optional(),
url: z.string().optional(),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
description: z.union([z.string(), z.literal("")]).optional(),
interval: z.number().optional(),
notifications: z.array(z.string()).optional(),
secret: z.string().optional(),
ignoreTlsErrors: z.boolean().optional(),
useAdvancedMatching: z.boolean().optional(),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
port: z.number().min(1).max(65535).optional(),
cpuAlertThreshold: z.number().optional(),
memoryAlertThreshold: z.number().optional(),
diskAlertThreshold: z.number().optional(),
tempAlertThreshold: z.number().optional(),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).optional(),
selectedDisks: z.array(z.string()).optional(),
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
geoCheckEnabled: z.boolean().optional(),
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
geoCheckInterval: z.number().min(300000).optional(),
dnsServer: z.string().optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
});
const refineStrategyType = (body: { type?: string; strategy?: string }, ctx: z.RefinementCtx) => {
if (body.strategy !== undefined && body.type !== undefined && body.type !== "pagespeed") {
ctx.addIssue({
code: "custom",
path: ["strategy"],
message: "Strategy is only valid for pagespeed monitors",
});
}
};
export const createMonitorBodyValidation = z
.object({
_id: z.string().optional(),
name: z.string().min(1, "Name is required"),
description: z.union([z.string(), z.literal("")]).optional(),
type: z.enum(MonitorTypes, "Invalid monitor type"),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
url: z.string().min(1, "URL is required"),
ignoreTlsErrors: z.boolean().default(false),
useAdvancedMatching: z.boolean().default(false),
port: z.number().optional(),
isActive: z.boolean().optional(),
interval: z.number().optional(),
cpuAlertThreshold: z.number().optional(),
memoryAlertThreshold: z.number().optional(),
diskAlertThreshold: z.number().optional(),
tempAlertThreshold: z.number().optional(),
notifications: z.array(z.string()).optional(),
secret: z.string().optional(),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
strategy: z.enum(PageSpeedStrategies).optional(),
selectedDisks: z.array(z.string()).optional(),
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
geoCheckEnabled: z.boolean().optional(),
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
geoCheckInterval: z.number().min(300000).optional(),
dnsServer: dnsServerValidation.optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
})
.superRefine(refineDnsHostname)
.superRefine(refineStrategyType);
export const editMonitorBodyValidation = z
.object({
name: z.string().optional(),
type: z.enum(MonitorTypes).optional(),
url: z.string().optional(),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
description: z.union([z.string(), z.literal("")]).optional(),
interval: z.number().optional(),
notifications: z.array(z.string()).optional(),
secret: z.string().optional(),
ignoreTlsErrors: z.boolean().optional(),
useAdvancedMatching: z.boolean().optional(),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
port: z.number().min(1).max(65535).optional(),
cpuAlertThreshold: z.number().optional(),
memoryAlertThreshold: z.number().optional(),
diskAlertThreshold: z.number().optional(),
tempAlertThreshold: z.number().optional(),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).optional(),
strategy: z.enum(PageSpeedStrategies).optional(),
selectedDisks: z.array(z.string()).optional(),
group: z.union([z.string().max(50).trim(), z.null(), z.literal("")]).optional(),
geoCheckEnabled: z.boolean().optional(),
geoCheckLocations: z.array(z.enum(GeoContinents)).optional(),
geoCheckInterval: z.number().min(300000).optional(),
dnsServer: dnsServerValidation.optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
})
.superRefine(refineDnsHostname)
.superRefine(refineStrategyType);
export const pauseMonitorParamValidation = z.object({
monitorId: z.string().min(1, "Monitor ID is required"),
@@ -124,49 +152,53 @@ export const getUptimeDetailsByIdQueryValidation = z.object({
normalize: booleanCoercion.optional(),
});
const importedMonitorSchema = z.object({
id: z.string().optional(),
userId: z.string().optional(),
teamId: z.string().optional(),
name: z.string().min(1, "Name is required"),
description: z.union([z.string(), z.literal("")]).optional(),
status: z.enum(["up", "down", "paused", "initializing", "maintenance", "breached"]).default("initializing"),
statusWindow: z.array(z.boolean()).default([]),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
type: z.enum(MonitorTypes, "Invalid monitor type"),
ignoreTlsErrors: z.boolean().default(false),
useAdvancedMatching: z.boolean().default(false),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
url: z.string().min(1, "URL is required"),
port: z.number().optional(),
isActive: z.boolean().default(true),
interval: z.number().default(60000),
uptimePercentage: z.number().optional(),
notifications: z.array(z.string()).default([]),
secret: z.string().optional(),
cpuAlertThreshold: z.number().default(100),
cpuAlertCounter: z.number().default(5),
memoryAlertThreshold: z.number().default(100),
memoryAlertCounter: z.number().default(5),
diskAlertThreshold: z.number().default(100),
diskAlertCounter: z.number().default(5),
tempAlertThreshold: z.number().default(100),
tempAlertCounter: z.number().default(5),
selectedDisks: z.array(z.string()).default([]),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
group: z.union([z.string().max(50).trim(), z.null()]).default(null),
geoCheckEnabled: z.boolean().default(false),
geoCheckLocations: z.array(z.enum(GeoContinents)).default([]),
geoCheckInterval: z.number().min(300000).default(300000),
dnsServer: z.string().optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
createdAt: z.string().optional(),
updatedAt: z.string().optional(),
});
const importedMonitorSchema = z
.object({
id: z.string().optional(),
userId: z.string().optional(),
teamId: z.string().optional(),
name: z.string().min(1, "Name is required"),
description: z.union([z.string(), z.literal("")]).optional(),
status: z.enum(["up", "down", "paused", "initializing", "maintenance", "breached"]).default("initializing"),
statusWindow: z.array(z.boolean()).default([]),
statusWindowSize: z.number().min(1).max(20).default(5),
statusWindowThreshold: z.number().min(1).max(100).default(60),
type: z.enum(MonitorTypes, "Invalid monitor type"),
ignoreTlsErrors: z.boolean().default(false),
useAdvancedMatching: z.boolean().default(false),
jsonPath: z.union([z.string(), z.literal("")]).optional(),
expectedValue: z.union([z.string(), z.literal("")]).optional(),
matchMethod: z.union([z.enum(MonitorMatchMethods), z.literal("")]).optional(),
url: z.string().min(1, "URL is required"),
port: z.number().optional(),
isActive: z.boolean().default(true),
interval: z.number().default(60000),
uptimePercentage: z.number().optional(),
notifications: z.array(z.string()).default([]),
secret: z.string().optional(),
cpuAlertThreshold: z.number().default(100),
cpuAlertCounter: z.number().default(5),
memoryAlertThreshold: z.number().default(100),
memoryAlertCounter: z.number().default(5),
diskAlertThreshold: z.number().default(100),
diskAlertCounter: z.number().default(5),
tempAlertThreshold: z.number().default(100),
tempAlertCounter: z.number().default(5),
selectedDisks: z.array(z.string()).default([]),
gameId: z.union([z.string(), z.literal("")]).optional(),
grpcServiceName: z.union([z.string(), z.literal("")]).default(""),
strategy: z.enum(PageSpeedStrategies).optional(),
group: z.union([z.string().max(50).trim(), z.null()]).default(null),
geoCheckEnabled: z.boolean().default(false),
geoCheckLocations: z.array(z.enum(GeoContinents)).default([]),
geoCheckInterval: z.number().min(300000).default(300000),
dnsServer: dnsServerValidation.optional(),
dnsRecordType: z.enum(DnsRecordTypes).optional(),
createdAt: z.string().optional(),
updatedAt: z.string().optional(),
})
.superRefine(refineDnsHostname)
.superRefine(refineStrategyType);
export const importMonitorsBodyValidation = z.object({
monitors: z.array(importedMonitorSchema).min(1, "At least one monitor is required"),
+11
View File
@@ -15,6 +15,17 @@ export const nameValidation = z
export const lowercaseEmailValidation = z.email().transform((val) => val.toLowerCase());
export const dnsServerValidation = z
.string()
.min(1, "DNS server is required")
.refine((v) => z.ipv4().safeParse(v).success || z.ipv6().safeParse(v).success, "Enter a valid IPv4 or IPv6 address (e.g. 8.8.8.8)");
// Hostname (FQDN) — labels of 1-63 alphanumerics/hyphens separated by dots,
// optionally prefixed with `_` for service labels (e.g. _dmarc, _imaps._tcp).
// No scheme, port, path, or whitespace. Total length ≤ 253. Kept in sync with
// the client-side regex in client/src/Validation/monitor.ts.
export const dnsHostnameRegex = /^(?=.{1,253}$)([a-zA-Z0-9_](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/;
export const booleanCoercion = z.preprocess((val) => {
if (val === "true" || val === true) return true;
if (val === "false" || val === false) return false;
@@ -8,7 +8,7 @@ const makeMaintenanceWindow = (overrides?: Partial<MaintenanceWindow>): Maintena
const end = new Date(now.getTime() + 60 * 60 * 1000); // 1 hour from now
return {
id: "mw-1",
monitorId: "mon-1",
monitorIds: ["mon-1"],
teamId: "team-1",
active: true,
name: "Test Maintenance",
@@ -109,6 +109,23 @@ describe("Heartbeat job: maintenance windows", () => {
expect(h.bufferStub.addToBuffer).toHaveBeenCalledTimes(1);
});
it("skips checks for every monitor covered by a group window", async () => {
const monitorA = makeMonitor({ id: "mon-a", name: "Monitor A" });
const monitorB = makeMonitor({ id: "mon-b", name: "Monitor B" });
h.monitorsRepo.seed(monitorA);
h.monitorsRepo.seed(monitorB);
// A single group window covers both monitors
h.maintenanceWindowsRepo.findByMonitorId.mockResolvedValue([makeMaintenanceWindow({ monitorIds: ["mon-a", "mon-b"] })]);
await h.heartbeatJob(monitorA);
await h.heartbeatJob(monitorB);
expect((await h.monitorsRepo.findById("mon-a", "team-1")).status).toBe("maintenance");
expect((await h.monitorsRepo.findById("mon-b", "team-1")).status).toBe("maintenance");
expect(h.networkService.requestStatus).not.toHaveBeenCalled();
});
it("skips checks when window is in the past (expired)", async () => {
const monitor = makeMonitor();
h.monitorsRepo.seed(monitor);
@@ -187,6 +187,28 @@ describe("DNSProvider", () => {
await expect(provider.handle(makeMonitor())).rejects.toThrow("Error performing DNS check");
});
it("strips scheme from url before querying the resolver", async () => {
const provider = new DNSProvider(createResolver);
const result = await provider.handle(makeMonitor({ url: "https://www.google.ca" }));
expect(mockResolverInstance.resolve4).toHaveBeenCalledWith("www.google.ca");
expect(result.payload?.hostname).toBe("www.google.ca");
});
it("strips port and path from url before querying the resolver", async () => {
const provider = new DNSProvider(createResolver);
await provider.handle(makeMonitor({ url: "example.com:53/some/path" }));
expect(mockResolverInstance.resolve4).toHaveBeenCalledWith("example.com");
});
it("passes a bare hostname through unchanged", async () => {
const provider = new DNSProvider(createResolver);
await provider.handle(makeMonitor({ url: "example.com" }));
expect(mockResolverInstance.resolve4).toHaveBeenCalledWith("example.com");
});
it("stringifies non-Error throws from outside timeRequest", async () => {
mockResolverInstance.setServers.mockImplementationOnce(() => {
throw 42;
@@ -37,7 +37,7 @@ const createService = (overrides?: {
const makeWindow = (overrides?: Partial<MaintenanceWindow>): MaintenanceWindow => ({
id: "mw-1",
monitorId: "mon-1",
monitorIds: ["mon-1"],
teamId: "team-1",
active: true,
name: "Scheduled Maintenance",
@@ -80,16 +80,16 @@ describe("MaintenanceWindowService", () => {
// ── createMaintenanceWindow ──────────────────────────────────────────────
describe("createMaintenanceWindow", () => {
it("creates a maintenance window for each monitor", async () => {
it("creates a single maintenance window covering all monitor IDs", async () => {
const { service, maintenanceWindowsRepository } = createService();
await service.createMaintenanceWindow(defaultCreateParams);
expect(maintenanceWindowsRepository.create).toHaveBeenCalledTimes(2);
expect(maintenanceWindowsRepository.create).toHaveBeenCalledTimes(1);
expect(maintenanceWindowsRepository.create).toHaveBeenCalledWith(
expect.objectContaining({
teamId: "team-1",
monitorId: "mon-1",
monitorIds: ["mon-1", "mon-2"],
name: "Scheduled Maintenance",
active: true,
duration: 60,
@@ -99,7 +99,6 @@ describe("MaintenanceWindowService", () => {
end: "2026-04-10T03:00:00Z",
})
);
expect(maintenanceWindowsRepository.create).toHaveBeenCalledWith(expect.objectContaining({ monitorId: "mon-2" }));
});
it("verifies monitor ownership via findByIds", async () => {
@@ -130,12 +129,13 @@ describe("MaintenanceWindowService", () => {
await expect(service.createMaintenanceWindow(defaultCreateParams)).resolves.toBeUndefined();
});
it("creates a single window when monitorIDs has one entry", async () => {
it("passes a single-element monitorIds array when only one monitor is provided", async () => {
const { service, maintenanceWindowsRepository } = createService();
await service.createMaintenanceWindow({ ...defaultCreateParams, monitorIDs: ["mon-1"] });
expect(maintenanceWindowsRepository.create).toHaveBeenCalledTimes(1);
expect(maintenanceWindowsRepository.create).toHaveBeenCalledWith(expect.objectContaining({ monitorIds: ["mon-1"] }));
});
});
@@ -248,5 +248,59 @@ describe("MaintenanceWindowService", () => {
expect(maintenanceWindowsRepository.updateById).toHaveBeenCalledWith("mw-1", "team-1", { active: false, repeat: 3600000 });
});
it("maps the monitors body field to monitorIds when calling the repository", async () => {
const { service, maintenanceWindowsRepository } = createService();
await service.editMaintenanceWindow({
id: "mw-1",
teamId: "team-1",
body: { monitors: ["mon-1", "mon-2"] },
});
expect(maintenanceWindowsRepository.updateById).toHaveBeenCalledWith("mw-1", "team-1", { monitorIds: ["mon-1", "mon-2"] });
});
it("verifies monitor ownership when monitors is in the body", async () => {
const { service, monitorsRepository } = createService();
await service.editMaintenanceWindow({
id: "mw-1",
teamId: "team-1",
body: { monitors: ["mon-1", "mon-2"] },
});
expect(monitorsRepository.findByIds).toHaveBeenCalledWith(["mon-1", "mon-2"]);
});
it("throws 403 when a new monitor belongs to a different team", async () => {
const monitorsRepository = createMonitorsRepo();
(monitorsRepository.findByIds as jest.Mock).mockResolvedValue([
{ id: "mon-1", teamId: "team-1" },
{ id: "mon-2", teamId: "team-other" },
]);
const { service, maintenanceWindowsRepository } = createService({ monitorsRepository });
await expect(
service.editMaintenanceWindow({
id: "mw-1",
teamId: "team-1",
body: { monitors: ["mon-1", "mon-2"] },
})
).rejects.toThrow("Unauthorized to edit maintenance window for one or more monitors");
expect(maintenanceWindowsRepository.updateById).not.toHaveBeenCalled();
});
it("does not call findByIds when monitors is not in the body", async () => {
const { service, monitorsRepository } = createService();
await service.editMaintenanceWindow({
id: "mw-1",
teamId: "team-1",
body: { name: "Updated Name" },
});
expect(monitorsRepository.findByIds).not.toHaveBeenCalled();
});
});
});
@@ -168,4 +168,24 @@ describe("editMaintenanceByIdWindowBodyValidation", () => {
});
expect(result.success).toBe(true);
});
it("accepts a body without a monitors field (monitors is optional on edit)", () => {
const result = editMaintenanceByIdWindowBodyValidation.safeParse({ name: "Updated Name" });
expect(result.success).toBe(true);
});
it("accepts a body with one or more monitors", () => {
const result = editMaintenanceByIdWindowBodyValidation.safeParse({ monitors: ["mon-1"] });
expect(result.success).toBe(true);
});
it("rejects an empty monitors array", () => {
const result = editMaintenanceByIdWindowBodyValidation.safeParse({ monitors: [] });
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues).toEqual(
expect.arrayContaining([expect.objectContaining({ message: "At least one monitor is required", path: ["monitors"] })])
);
}
});
});
@@ -51,6 +51,51 @@ describe("monitorValidation — DNS fields", () => {
expect(parsed.dnsServer).toBeUndefined();
expect(parsed.dnsRecordType).toBeUndefined();
});
it("rejects a DNS monitor whose url has a scheme or path", () => {
for (const badUrl of ["https://example.com", "example.com/path", "example.com:53", " example.com"]) {
expect(() =>
createMonitorBodyValidation.parse({
...baseDnsBody,
url: badUrl,
dnsServer: "8.8.8.8",
dnsRecordType: "A",
})
).toThrow();
}
});
it("rejects a DNS monitor with an invalid dnsServer", () => {
expect(() =>
createMonitorBodyValidation.parse({
...baseDnsBody,
dnsServer: "not-an-ip",
dnsRecordType: "A",
})
).toThrow();
});
it("accepts service labels with leading underscore (DMARC, SRV, ACME)", () => {
for (const url of ["_dmarc.example.com", "_imaps._tcp.example.com", "_acme-challenge.example.com"]) {
const parsed = createMonitorBodyValidation.parse({
...baseDnsBody,
url,
dnsServer: "8.8.8.8",
dnsRecordType: "TXT",
});
expect(parsed.url).toBe(url);
}
});
it("does not enforce the hostname rule for non-DNS monitors", () => {
const parsed = createMonitorBodyValidation.parse({
name: "HTTP check",
type: "http",
url: "https://example.com/some/path",
});
expect(parsed.url).toBe("https://example.com/some/path");
});
});
describe("editMonitorBodyValidation", () => {
@@ -84,3 +129,96 @@ describe("monitorValidation — DNS fields", () => {
});
});
});
describe("monitorValidation — strategy gating", () => {
describe("createMonitorBodyValidation", () => {
it("accepts strategy on pagespeed monitors", () => {
const parsed = createMonitorBodyValidation.parse({
name: "PS check",
type: "pagespeed",
url: "https://example.com",
strategy: "mobile",
});
expect(parsed.strategy).toBe("mobile");
});
it("accepts pagespeed monitors without a strategy", () => {
const parsed = createMonitorBodyValidation.parse({
name: "PS check",
type: "pagespeed",
url: "https://example.com",
});
expect(parsed.strategy).toBeUndefined();
});
it("rejects strategy on non-pagespeed monitor types", () => {
for (const type of ["http", "ping", "docker", "port", "game", "grpc", "websocket", "dns", "hardware"] as const) {
expect(() =>
createMonitorBodyValidation.parse({
name: "wrong-type check",
type,
url: type === "dns" ? "example.com" : "https://example.com",
strategy: "desktop",
})
).toThrow();
}
});
it("allows non-pagespeed monitors without a strategy", () => {
const parsed = createMonitorBodyValidation.parse({
name: "HTTP check",
type: "http",
url: "https://example.com",
});
expect(parsed.strategy).toBeUndefined();
});
});
describe("editMonitorBodyValidation", () => {
it("rejects strategy when type is explicitly non-pagespeed", () => {
expect(() =>
editMonitorBodyValidation.parse({
type: "http",
strategy: "mobile",
})
).toThrow();
});
it("allows strategy when type is omitted (partial edit)", () => {
const parsed = editMonitorBodyValidation.parse({
strategy: "mobile",
});
expect(parsed.strategy).toBe("mobile");
});
});
describe("importMonitorsBodyValidation", () => {
it("does not inject a default strategy on imported HTTP monitors", () => {
const parsed = importMonitorsBodyValidation.parse({
monitors: [
{
name: "Imported HTTP",
type: "http",
url: "https://example.com",
},
],
});
expect(parsed.monitors[0].strategy).toBeUndefined();
});
it("rejects strategy on imported non-pagespeed monitors", () => {
expect(() =>
importMonitorsBodyValidation.parse({
monitors: [
{
name: "Imported HTTP",
type: "http",
url: "https://example.com",
strategy: "desktop",
},
],
})
).toThrow();
});
});
});