Compare commits

..
Author SHA1 Message Date
gorkem-bwl 9ad1e261a4 Merge branch 'develop' into fix/login-error-handling 2025-10-16 05:01:17 -04:00
gorkem-bwl 05442af050 fix: apply prettier formatting to userService.js
- Fixed all prettier formatting issues in userService.js
- All files now pass prettier format check
- Maintained null checks and error handling improvements
2025-09-11 23:55:58 -04:00
gorkem-bwl 25d538504c resolve: merge conflicts with develop branch
- Resolved conflict in translationService.js by using develop branch path format
- Updated locales directory path to use 'src/locales' format
- Maintained existing login error handling improvements
2025-09-11 22:17:13 -04:00
gorkem-bwl e823533809 fix: apply prettier formatting and address code quality issues
- Fix prettier formatting issues in userService.js
- Add null checks before password comparisons to prevent runtime errors
- Improve error logging while maintaining security by not exposing sensitive info
- Address CodeRabbit and LlamaPReview feedback
2025-09-11 22:14:08 -04:00
gorkem-bwl a03996d54b fix: resolve login error handling issues
- Fix translation service to load locales from correct path (src/locales)
- Improve login security to return generic error message for both invalid email and wrong password
- Make frontend error handling generic to display backend error messages properly
- Remove hardcoded string matching in favor of HTTP status code checks

Fixes login flow returning raw localization keys instead of user-facing messages

Fixes #2768
2025-08-12 21:09:14 -04:00
79 changed files with 1902 additions and 15818 deletions

No files matched your search

-1
View File
@@ -88,4 +88,3 @@ jobs:
docker compose down
docker compose pull
docker compose up -d
docker system prune -af
-993
View File
@@ -1,993 +0,0 @@
# Checkmate Codebase Architecture - Docker Monitoring Integration Guide
## 1. PROJECT STRUCTURE
### Directory Layout
```
Checkmate/
├── server/ # Backend Node.js/Express
│ ├── src/
│ │ ├── db/v1|v2/ # Database (MongoDB)
│ │ ├── service/v1|v2/ # Business logic
│ │ ├── routes/v1|v2/ # API routes
│ │ ├── controllers/v1|v2/ # HTTP request handlers
│ │ ├── middleware/v1/ # Express middleware
│ │ ├── config/ # Service initialization
│ │ ├── validation/ # Input validation
│ │ └── utils/ # Helper functions
│ └── package.json # Dependencies (Node >=20)
├── client/ # Frontend React + TypeScript
│ ├── src/
│ │ ├── Components/v1|v2/ # UI Components
│ │ ├── Pages/v1|v2/ # Page layouts
│ │ ├── Hooks/ # React hooks (data fetching)
│ │ ├── Features/ # Redux slices
│ │ └── Utils/ # Utilities & API client
│ └── package.json # React, Vite, MUI
└── docker/ # Deployment configs
```
### Technology Stack
**Backend:**
- Express 4.19 (HTTP server)
- MongoDB 8.3 (database)
- Mongoose (ODM)
- BullMQ 5.41 (job queue) - V2 only
- super-simple-scheduler 1.4 (job scheduling) - V1
- Dockerode 4.0.6 (Docker API client)
- JWT authentication
- Winston (logging)
**Frontend:**
- React 18.3 + TypeScript
- Vite (build tool)
- MUI v6 (Material-UI)
- Redux Toolkit (state management)
- Axios (HTTP client)
- React Router (navigation)
- i18next (internationalization)
**Architectures:**
- V1: Simpler, SuperSimpleQueue-based job scheduling
- V2: TypeScript-based, BullMQ, more structured (in development)
---
## 2. MONITOR TYPES & IMPLEMENTATION
### Supported Monitor Types
Defined in `/server/src/db/v1/models/Monitor.js` line 46:
```javascript
type: {
enum: ["http", "ping", "pagespeed", "hardware", "docker", "port", "game"],
required: true
}
```
### How Monitor Types Are Handled
#### Request Dispatch (NetworkService)
**Location:** `/server/src/service/v1/infrastructure/networkService.js` (580 lines)
Entry point: `requestStatus(monitor)` - Routes to type-specific handlers:
```javascript
async requestStatus(monitor) {
switch(monitor.type) {
case "ping": return await this.requestPing(monitor);
case "http": return await this.requestHttp(monitor);
case "pagespeed": return await this.requestPageSpeed(monitor);
case "hardware": return await this.requestHardware(monitor);
case "docker": return await this.requestDocker(monitor);
case "port": return await this.requestPort(monitor);
case "game": return await this.requestGame(monitor);
}
}
```
#### DOCKER IMPLEMENTATION (Lines 289-383)
```javascript
async requestDocker(monitor) {
// Uses Dockerode to connect to /var/run/docker.sock
const docker = new this.Docker({
socketPath: "/var/run/docker.sock",
handleError: true,
});
// Container matching (priority-based):
// 1. Exact full ID match (64-char)
// 2. Exact name match (case-insensitive)
// 3. Partial ID match (backwards compatibility)
// Returns: { status: bool, code: int, message: string, responseTime: ms }
}
```
**Docker Monitor Storage:**
- `monitor.url`: Container ID or name (e.g., "my-app" or "a1b2c3d4...")
- `monitor.port`: Not used for Docker
- Returns: Only status and response time (no detailed metrics)
#### HARDWARE IMPLEMENTATION (Lines 279-287)
```javascript
async requestHardware(monitor) {
return await this.requestHttp(monitor); // Delegates to HTTP!
}
```
Hardware monitors send HTTP requests to Capture API endpoint with secret authentication.
### Hardware/Docker Check Data Structure
**Location:** `/server/src/db/v1/models/Check.js` (176 lines)
Check schema includes:
```javascript
// Common fields
monitorId, teamId, type, status, responseTime, message
// Hardware/Docker specific (capture data):
cpu: {
physical_core, logical_core, frequency, temperature[],
free_percent, usage_percent
},
memory: {
total_bytes, available_bytes, used_bytes, usage_percent
},
disk: [{
read_speed_bytes, write_speed_bytes,
total_bytes, free_bytes, usage_percent
}],
host: { os, platform, kernel_version },
errors: [{ metric[], err }],
capture: { version, mode },
net: [{ name, bytes_sent, bytes_recv, ... }]
```
**TTL:** Auto-deletes after 30 days
**Indexes:** monitorId, type, status, updatedAt (optimized for queries)
---
## 3. DATABASE SCHEMA
### Core Models
#### Monitor Model
**File:** `/server/src/db/v1/models/Monitor.js` (208 lines)
```javascript
{
userId: ObjectId (immutable, required),
teamId: ObjectId (immutable, required),
name: String (required),
description: String,
type: String (enum: http|ping|pagespeed|hardware|docker|port|game),
url: String (required) // container name/ID for docker
port: Number,
interval: Number (ms, default: 60000),
isActive: Boolean (default: true),
status: Boolean, // Current up/down
statusWindow: [Boolean], // Last N checks
statusWindowSize: Number (default: 5),
statusWindowThreshold: Number (default: 60),
// Hardware/Docker thresholds
thresholds: {
usage_cpu: Number (0-1),
usage_memory: Number (0-1),
usage_disk: Number (0-1),
usage_temperature: Number
},
// Notification thresholds
alertThreshold: Number (default: 5),
cpuAlertThreshold, memoryAlertThreshold, diskAlertThreshold, tempAlertThreshold,
// Relationships
notifications: [ObjectId], // refs to Notification model
// Advanced
secret: String, // For Capture API auth
ignoreTlsErrors: Boolean,
jsonPath: String,
expectedValue: String,
matchMethod: String (equal|include|regex),
gameId: String,
group: String (max 50 chars),
// Computed
uptimePercentage: Number,
timestamps: true // createdAt, updatedAt
}
// Indexes
MonitorSchema.index({ teamId: 1, type: 1 });
// Pre-hooks
pre("findOneAndDelete"): Deletes checks, stats, removes from status pages
pre("deleteMany"): Cascade deletes
pre("save"): Syncs alertThresholds
pre("findOneAndUpdate"): Updates thresholds
```
#### Check Model
**File:** `/server/src/db/v1/models/Check.js`
```javascript
{
monitorId: ObjectId (ref: Monitor, immutable, indexed),
teamId: ObjectId (ref: Team, immutable, indexed),
type: String (enum: http|ping|pagespeed|hardware|docker|port|game, indexed),
status: Boolean (indexed),
responseTime: Number,
timings: Object,
statusCode: Number,
message: String,
// Acknowledgment
ack: Boolean (default: false),
ackAt: Date,
// Hardware fields (see above)
cpu, memory, disk[], host, errors[], capture, net[]
// PageSpeed only
accessibility, bestPractices, seo, performance, audits,
// Expiry
expiry: Date (TTL index: 30 days),
timestamps: true
}
// Indexes
CheckSchema.index({ updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: -1 });
CheckSchema.index({ teamId: 1, updatedAt: -1 });
```
#### MonitorStats Model
**File:** `/server/src/db/v1/models/MonitorStats.js`
```javascript
{
monitorId: ObjectId (ref: Monitor, immutable, indexed),
avgResponseTime: Number,
totalChecks: Number,
totalUpChecks: Number,
totalDownChecks: Number,
uptimePercentage: Number,
lastCheckTimestamp: Number,
lastResponseTime: Number,
timeOfLastFailure: Number,
timestamps: true
}
```
### Database Access Layer
**Location:** `/server/src/db/v1/modules/`
- `MonitorModule.js` (593 lines) - Monitor CRUD + aggregations
- `CheckModule.js` - Check recording
- `MonitorModuleQueries.js` - MongoDB aggregation pipelines
**Key Methods:**
```javascript
// Creation
Monitor.createMonitor({ body, teamId, userId })
Monitor.createBulkMonitors(monitors)
// Retrieval
Monitor.getMonitorById(id)
Monitor.getMonitorsByTeamId()
Monitor.getMonitorStatsById()
Monitor.getHardwareDetailsById()
// Updates
Monitor.updateMonitor(id, updateData)
// Deletions
Monitor.deleteMonitor(id)
```
---
## 4. API PATTERNS
### REST Endpoint Structure
**Base:** `/api/v1/`
#### Monitor Routes
**File:** `/server/src/routes/v1/monitorRoute.js`
```
GET /monitors getAllMonitors
POST /monitors createMonitor
DELETE /monitors deleteAllMonitors (superadmin)
GET /monitors/:monitorId getMonitorById
PUT /monitors/:monitorId editMonitor (admin)
DELETE /monitors/:monitorId deleteMonitor (admin)
GET /monitors/team getMonitorsByTeamId
GET /monitors/team/with-checks getMonitorsWithChecksByTeamId
GET /monitors/team/summary getMonitorsSummaryByTeamId
GET /monitors/team/groups getGroupsByTeamId
GET /monitors/stats/:monitorId getMonitorStatsById
GET /monitors/uptime/details/:monitorId getUptimeDetailsById
GET /monitors/hardware/details/:monitorId getHardwareDetailsById
POST /monitors/pause/:monitorId pauseMonitor (admin)
POST /monitors/demo addDemoMonitors
POST /monitors/bulk createBulkMonitors (CSV upload)
POST /monitors/test-email sendTestEmail
GET /monitors/games getAllGames
GET /monitors/certificate/:monitorId fetchCertificate
```
#### Check Routes
**File:** `/server/src/routes/v1/checkRoute.js`
```
GET /checks/:monitorId getChecksByMonitorId
GET /checks/team/:teamId getChecksByTeamId
GET /checks/:monitorId/:checkId getCheckById
PUT /checks/:checkId updateCheck (ack)
```
### Request/Response Pattern
**Create Monitor Request:**
```javascript
POST /api/v1/monitors
Authorization: Bearer <JWT>
Content-Type: application/json
{
name: "My Docker Container",
description: "Monitors app container",
type: "docker",
url: "my-app-container", // Container name
interval: 60000, // 1 minute
isActive: true,
secret: "api-key-for-capture", // If using hardware monitoring
notifications: ["notif-id-1"],
thresholds: {
usage_cpu: 0.8, // 80%
usage_memory: 0.9, // 90%
usage_disk: 0.95
},
alertThreshold: 5, // Consecutive failures
statusWindowSize: 5, // Last 5 checks
statusWindowThreshold: 60 // % threshold
}
Response 200:
{
data: {
_id: "monitor-id",
name: "My Docker Container",
type: "docker",
status: true,
interval: 60000,
...
},
msg: "Monitor created successfully"
}
```
**Edit Monitor Request:**
```javascript
PUT /api/v1/monitors/:monitorId
{
name: "Updated Name",
interval: 120000,
thresholds: { usage_cpu: 0.85 },
// Partial updates allowed
}
```
### Authentication & Authorization
**JWT Middleware:** `/server/src/middleware/v1/verifyJWT.js`
- Header: `Authorization: Bearer <token>`
- Validates signature using `jwtSecret` from AppSettings
- Extracts user info: `req.user = { userId, teamId, role, ... }`
**Role-Based Access:**
```javascript
// isAllowed middleware checks req.user.role
router.post("/monitors", isAllowed(["admin", "superadmin"]), createMonitor);
router.delete("/monitors/:monitorId", isAllowed(["admin", "superadmin"]), deleteMonitor);
```
### Validation
**File:** `/server/src/validation/joi.js`
```javascript
const createMonitorBodyValidation = joi.object({
name: joi.string().required(),
description: joi.string().required(),
type: joi.string().required(),
url: joi.string().required(),
interval: joi.number(),
port: joi.number(),
thresholds: joi.object().keys({
usage_cpu: joi.number(),
usage_memory: joi.number(),
usage_disk: joi.number(),
usage_temperature: joi.number(),
}),
notifications: joi.array().items(joi.string()),
secret: joi.string(),
// ... more fields
});
```
---
## 5. POLLING/JOBS IMPLEMENTATION
### Job Queue Architecture
#### V1: SuperSimpleScheduler (Production)
**Files:**
- `/server/src/service/v1/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js`
- `/server/src/service/v1/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js`
**Job Lifecycle:**
1. **Initialization** (on server startup):
```javascript
// Load all monitors from DB
const monitors = await db.monitorModule.getAllMonitors();
for (const monitor of monitors) {
// Add job with random offset (0-100ms)
this.addJob(monitor._id, monitor);
}
// Register job template
scheduler.addTemplate("monitor-job", this.helper.getMonitorJob());
```
2. **Job Template** (executed per interval):
```javascript
getMonitorJob = () => {
return async (monitor) => {
// Check maintenance window
if (await this.isInMaintenanceWindow(monitorId, teamId)) {
return; // Skip
}
// Execute monitor check
const networkResponse = await this.networkService.requestStatus(monitor);
// Update monitor status
const { monitor: updated, statusChanged } =
await this.statusService.updateStatus(networkResponse);
// Send notifications if status changed
if (statusChanged) {
await this.notificationService.handleNotifications({
...networkResponse,
monitor: updated,
prevStatus,
statusChanged
});
}
};
};
```
3. **Job Control:**
```javascript
// Add job
addJob(monitorId, monitor) {
scheduler.addJob({
id: monitorId.toString(),
template: "monitor-job",
repeat: monitor.interval, // Milliseconds
active: monitor.isActive,
data: monitor.toObject()
});
}
// Pause/Resume
pauseJob(monitor) { scheduler.pauseJob(monitor._id); }
resumeJob(monitor) { scheduler.resumeJob(monitor._id); }
// Update interval
updateJob(monitor) {
scheduler.updateJob(monitor._id, {
repeat: monitor.interval,
data: monitor.toObject()
});
}
// Delete
deleteJob(monitor) { scheduler.removeJob(monitor._id); }
```
#### V2: BullMQ (TypeScript, Planned)
**Files:**
- `/server/src/service/v2/infrastructure/JobQueue.ts`
- `/server/src/service/v2/infrastructure/JobGenerator.ts`
**Key Differences:**
- Uses Redis backing store
- TypeScript interfaces (type safety)
- More robust queue management
- Cleanup jobs for orphaned checks
```typescript
// Cleanup job runs every 24 hours
scheduler.addJob({
id: "cleanup-orphaned-checks",
template: "cleanup-job",
repeat: 24 * 60 * 60 * 1000,
active: true
});
```
### Monitor Execution Flow
```
Monitor Created/Updated
↓
MonitorService.createMonitor()
↓
jobQueue.addJob(monitor)
↓
Job scheduled at interval
↓
[Job Execution]
├─ Check maintenance window
├─ NetworkService.requestStatus(monitor)
│ └─ Routes to type handler (requestDocker, requestHttp, etc)
├─ Create Check record (database)
├─ StatusService.updateMonitorStatus()
│ └─ Updates Monitor.status field
├─ MonitorStatsService.updateStats()
├─ If status changed → NotificationService.handleNotifications()
└─ Job completes / reschedules for next interval
```
### Status Update Logic
**Location:** `/server/src/service/v1/infrastructure/statusService.js`
```javascript
async updateStatus(networkResponse) {
// networkResponse = { monitorId, type, status, code, message, responseTime }
// 1. Create Check record
const check = await Check.create({
monitorId, teamId, type, status,
responseTime, statusCode: code, message
});
// 2. Get previous status
const prevStatus = monitor.status;
// 3. Apply statusWindow logic (sliding window of checks)
monitor.statusWindow.push(status);
if (monitor.statusWindow.length > monitor.statusWindowSize) {
monitor.statusWindow.shift();
}
// 4. Determine if DOWN (majority of window is false)
const downCount = monitor.statusWindow.filter(s => !s).length;
const isDown = (downCount / monitor.statusWindowSize) >
(monitor.statusWindowThreshold / 100);
monitor.status = isDown ? false : true;
// 5. Return status change info
return {
monitor: await monitor.save(),
statusChanged: prevStatus !== monitor.status,
prevStatus
};
}
```
---
## 6. FRONTEND COMPONENTS
### Monitor Management Pages
#### Infrastructure Monitors (Hardware/Docker)
**Location:** `/client/src/Pages/v1/Infrastructure/`
```
Infrastructure/
├── Create/
│ ├── index.jsx (Main form - 10K lines)
│ ├── Components/
│ │ ├── MonitorStatusHeader.jsx
│ │ ├── MonitorActionButtons.jsx
│ │ └── CustomAlertsSection.jsx
│ └── hooks/
│ ├── useInfrastructureMonitorForm.jsx
│ ├── useValidateInfrastructureForm.jsx
│ └── useInfrastructureSubmit.jsx
├── Details/
├── Monitors/
│ └── Components/
│ └── MonitorsTable.jsx
```
#### Form Structure (useInfrastructureMonitorForm hook)
```javascript
const [infrastructureMonitor, setInfrastructureMonitor] = useState({
url: "", // Container name/IP
name: "", // Display name
notifications: [], // Notification IDs
interval: 0.25, // Minutes (0.25 = 15s, 1 = 60s)
// Threshold toggles
cpu: false,
usage_cpu: "", // Percentage
memory: false,
usage_memory: "",
disk: false,
usage_disk: "",
temperature: false,
usage_temperature: "",
secret: "", // Capture API secret
statusWindowSize: 5,
statusWindowThreshold: 60
});
```
**Frequency Options:**
```javascript
[
{ _id: 0.25, name: "15 Seconds" },
{ _id: 0.5, name: "30 Seconds" },
{ _id: 1, name: "1 Minute" },
{ _id: 2, name: "2 Minutes" },
{ _id: 5, name: "5 Minutes" },
{ _id: 10, name: "10 Minutes" }
]
```
#### Form Submission (useInfrastructureSubmit hook)
```javascript
// Converts frontend form → backend model
const finalForm = {
url: `http${https ? "s" : ""}://` + infrastructureMonitor.url,
name: infrastructureMonitor.name || infrastructureMonitor.url,
interval: infrastructureMonitor.interval * 60000, // Convert to ms
type: "hardware", // Always "hardware" for infrastructure monitors
// Thresholds (convert % to decimal 0-1)
thresholds: {
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {})
},
notifications: infrastructureMonitor.notifications
};
// API call
isCreate ?
await createMonitor({ monitor: finalForm, redirect: "/infrastructure" }) :
await updateMonitor({ monitor: finalForm, redirect: "/infrastructure" });
```
### Monitor Display Components
#### Monitor Status Component
**Location:** `/client/src/Components/v2/Monitors/MonitorStatus.tsx`
Displays:
- Status indicator (up/down)
- Response time
- Last check time
- Incident badges
#### Monitoring Hooks
**Location:** `/client/src/Hooks/v1/monitorHooks.js`
```javascript
// Fetch monitors
useFetchMonitorsByTeamId({ types, limit, page, ... })
useFetchMonitorsWithSummary({ types, monitorUpdateTrigger })
useFetchMonitorsWithChecks({ types, limit, ... })
// Fetch individual monitor
useFetchHardwareMonitorById({ monitorId, updateTrigger })
useFetchStatsByMonitorId({ monitorId, dateRange, ... })
// Manage monitors
useCreateMonitor() // POST /monitors
useUpdateMonitor() // PUT /monitors/:id
useDeleteMonitor() // DELETE /monitors/:id
usePauseMonitor() // POST /monitors/pause/:id
```
### Network Service (API Client)
**Location:** `/client/src/Utils/NetworkService.js` (1157 lines)
```javascript
// Constructor
constructor(store, dispatch, navigate) {
// Axios instance with:
// - Bearer token injection
// - Language header
// - 401 redirect to login
// - Network error handling
}
// Monitor endpoints
async createMonitor(config) {
return this.axiosInstance.post(`/monitors`, config.monitor);
}
async updateMonitor(config) {
return this.axiosInstance.put(`/monitors/${config.monitorId}`, config.monitor);
}
async getMonitorsByTeamId(config) {
// Query params: limit, types[], page, rowsPerPage, filter, field, order
return this.axiosInstance.get(`/monitors/team?...`);
}
async getHardwareDetailsByMonitorId(config) {
return this.axiosInstance.get(`/monitors/hardware/details/${config.monitorId}`);
}
async getStatsByMonitorId(config) {
// Query params: sortOrder, limit, dateRange, numToDisplay, normalize
return this.axiosInstance.get(`/monitors/stats/${config.monitorId}?...`);
}
```
---
## 7. AUTHENTICATION & API KEYS
### User Authentication (JWT)
**Registration/Login:**
```javascript
// POST /auth/register
{
firstName: "John",
lastName: "Doe",
email: "john@example.com",
password: "SecurePass123!"
}
Response:
{
user: { _id, email, role, teamId, ... },
token: "eyJhbGciOiJIUzI1NiIs..." // JWT
}
```
**Token Storage:** Redux store (`Features/Auth/authSlice`)
**Token Injection:** Automatic by NetworkService
```javascript
config.headers.Authorization = `Bearer ${authToken}`;
```
### Monitor-Specific Authentication
#### For Hardware/Docker Monitors via Capture API
Monitors can have a `secret` field for authenticating requests to the Capture API:
```javascript
{
type: "hardware",
url: "http://192.168.1.100:3000", // Capture endpoint
secret: "api-key-12345", // Passed to Capture API
thresholds: { ... }
}
```
**Implementation:** The secret is stored in the Monitor model and could be:
1. Sent as HTTP header: `Authorization: Bearer <secret>`
2. Sent as query param: `?secret=<secret>`
3. Sent in request body for POST requests
---
## 8. CONFIGURATION & USER SETTINGS
### Global Settings
**Model:** `/server/src/db/v1/models/AppSettings.js`
```javascript
{
jwtSecret: String, // For signing JWTs
sslCertificate: String, // SSL cert content
smtpConfig: Object, // Email settings
globalThresholds: { // Default thresholds
cpu: Number,
memory: Number,
disk: Number,
temperature: Number
},
siteTitle: String,
defaultLanguage: String,
maintenanceMode: Boolean
}
```
**Fetching Settings:**
```javascript
// Frontend
useFetchGlobalSettings()
→ NetworkService.getGlobalSettings()
→ GET /settings
// Backend
SettingsService.loadSettings()
→ Loads from AppSettings collection
```
### Monitor Configuration UI Flow
1. **Create Page:** `/infrastructure/create`
- Fetch global settings for default thresholds
- Form includes:
- Monitor name
- URL/Container name
- Interval (dropdown)
- CPU/Memory/Disk/Temp thresholds (checkboxes + inputs)
- Notification channels (multi-select)
- Secret (if using Capture API)
2. **Edit Page:** `/infrastructure/configure/:monitorId`
- Load existing monitor data
- Update form fields
- Save changes with PUT request
3. **Details Page:** `/infrastructure/:monitorId`
- Display monitor stats
- Show uptime graph
- List recent checks
- Status history
### Team-Based Isolation
**Access Control:**
```javascript
// All queries filtered by teamId
await Monitor.find({ teamId: req.user.teamId });
// verifyTeamAccess middleware
await verifyTeamAccess(req.user.teamId, req.params.monitorId);
```
---
## KEY PATTERNS FOR DOCKER MONITORING INTEGRATION
### 1. Adding Docker Monitor Type
Already supported! Located in:
- `Monitor.schema` type enum ✓
- `NetworkService.requestDocker()` ✓
- `Check.schema` with type ✓
### 2. Docker-Specific Data Collection
Currently: Only status + response time
**To Add Detailed Metrics:**
- Extend `Check.schema` with Docker stats fields
- Modify `NetworkService.requestDocker()` to call `container.stats()`
- Stream stats to `Check.docker` field
### 3. Capture API Integration (Hardware Monitoring)
**Flow:**
```
Monitor with type="hardware" and url="http://capture-endpoint"
↓
NetworkService.requestHardware()
↓ (delegates to)
NetworkService.requestHttp()
↓
Expects JSON response: { cpu, memory, disk, net, ... }
↓
Check record stores full payload in hardware fields
```
### 4. Database Queries
**Get hardware checks:**
```javascript
Check.find({
monitorId: id,
type: "hardware",
createdAt: { $gte: startDate, $lte: endDate }
})
.sort({ createdAt: -1 })
.limit(100)
```
### 5. UI Display
- Stats dashboard: `/infrastructure/:monitorId`
- Uptime details: `/monitor/uptime/details/:monitorId`
- Hardware details: `/monitor/hardware/details/:monitorId`
---
## SERVICE ARCHITECTURE
### Service Registry Pattern
**Location:** `/server/src/service/v1/system/serviceRegistry.js`
```javascript
// Singleton pattern
ServiceRegistry.set(serviceName, serviceInstance);
const service = ServiceRegistry.get(serviceName);
```
### Service Dependencies
**Initialization:** `/server/src/config/services.js`
```javascript
// Infrastructure services
new NetworkService({
axios, got, https, jmespath, GameDig, ping,
logger, http, Docker, // ← Docker client injected
net, stringService, settingsService
})
// Business services
new MonitorService({
db, settingsService, jobQueue,
stringService, emailService, logger
})
```
---
## KEY FILES SUMMARY
| Component | File | Lines | Purpose |
|-----------|------|-------|---------|
| Monitor Model | `server/src/db/v1/models/Monitor.js` | 209 | Schema, hooks |
| Check Model | `server/src/db/v1/models/Check.js` | 177 | Check records, TTL |
| NetworkService | `server/src/service/v1/infrastructure/networkService.js` | 580 | Type handlers |
| MonitorService | `server/src/service/v1/business/monitorService.js` | 277 | CRUD, validation |
| MonitorModule | `server/src/db/v1/modules/monitorModule.js` | 593 | DB queries |
| JobQueue | `server/src/service/v1/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js` | 177 | Job scheduling |
| MonitorController | `server/src/controllers/v1/monitorController.js` | 475 | HTTP handlers |
| MonitorRoute | `server/src/routes/v1/monitorRoute.js` | 61 | Endpoint definitions |
| Frontend Hooks | `client/src/Hooks/v1/monitorHooks.js` | 500+ | Data fetching |
| NetworkService (FE) | `client/src/Utils/NetworkService.js` | 1157 | API client |
| Form Hook | `client/src/Pages/v1/Infrastructure/Create/hooks/useInfrastructureMonitorForm.jsx` | 97 | Form state |
---
## DEPLOYMENT & DOCKER INTEGRATION
### Docker-Compose Setup
**Files:** `/docker/dev/docker-compose.yaml`, `/docker/prod/docker-compose.yaml`
**Volumes for Docker Monitoring:**
```yaml
volumes:
- /var/run/docker.sock:/var/run/docker.sock # Required for Dockerode
```
### Environment Variables
**Backend (.env):**
```
MONGODB_URI=mongodb://mongo:27017/checkmate
JWT_SECRET=your-secret-key
NODE_ENV=production|development
PORT=5000
```
**Frontend (.env):**
```
VITE_APP_API_BASE_URL=http://localhost:5000/api/v1
```
+4 -4
View File
@@ -66,7 +66,7 @@ cd Checkmate
Navigate to the Docker dev directory:
```bash
cd docker/dev
cd server/docker/dev
```
Build the Docker images:
@@ -78,13 +78,13 @@ Build the Docker images:
Run MongoDB container:
```bash
docker run -d -p 27017:27017 -v uptime_mongo_data:/data/db --name uptime_database_mongo mongo:6.0
docker run -d -p 27017:27017 -v $(pwd)/mongo/data:/data/db --name uptime_database_mongo uptime_database_mongo
```
Navigate back to the root directory:
```bash
cd ../..
cd ../../..
```
#### Step 3: Set Up the Backend (Server)
@@ -161,7 +161,7 @@ Start the frontend:
npm run dev
```
The client will run at `http://localhost:5173`.
The client will run at `http://localhost:5173`.
#### Step 5: Access the Application
-11325
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -52,7 +52,7 @@ Usage instructions can be found [here](https://docs.checkmate.so/checkmate-2.1).
See installation instructions in [Checkmate documentation portal](https://docs.checkmate.so/checkmate-2.1/users-guide/quickstart).
Alternatively, you can also use [Elestio](https://elest.io/open-source/checkmate), [K8s](./charts/helm/checkmate/INSTALLATION.md), [Sive Host](https://sive.host) (South Africa) or [Pikapods](https://www.pikapods.com/) to quickly spin off a Checkmate instance. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
Alternatively, you can also use [Coolify](https://coolify.io/), [Elestio](https://elest.io/open-source/checkmate), [K8s](./charts/helm/checkmate/INSTALLATION.md), [Sive Host](https://sive.host) (South Africa) or [Pikapods](https://www.pikapods.com/) to quickly spin off a Checkmate instance. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions.
### Using a Custom CA
@@ -162,7 +162,6 @@ Here's how you can contribute:
4. Open an issue if you believe you've encountered a bug.
5. Check for good-first-issue's if you are a newcomer.
6. Make a pull request to add new features/make quality-of-life improvements/fix bugs.
7. Check out this interactive walkthrough of the `Checkmate` codebase on CodeCanvas [here](https://www.code-canvas.com/?session=unauthenticatedGithub&repo=Checkmate&owner=bluewave-labs&branch=develop&OnboardingTutorial=true). To refine existing dataflow simulation or create new ones, follow the quick tutorial [here](https://docs.code-canvas.com/updating-diagram).
<a href="https://github.com/bluewave-labs/checkmate/graphs/contributors">
<img src="https://contrib.rocks/image?repo=bluewave-labs/checkmate" />
-4
View File
@@ -21,10 +21,6 @@ cd checkmate/charts/helm/checkmate
Edit `values.yaml` to update:
- `client.ingress.host` and `server.ingress.host` with your domain names
- `server.protocol` (usually http or https)
- **If upgrading**: Migrate persistence settings from flat structure to nested:
- Old: `persistence.mongodbSize` → New: `persistence.mongo.size`
- Old: `persistence.redisSize` → New: `persistence.redis.size`
- Add: `persistence.mongo.storageClass` and `persistence.redis.storageClass` (leave empty for default)
- Secrets under the `secrets` section (`JWT_SECRET`, email credentials, API keys, etc.) — replace all change_me values
### 3. Deploy the Helm chart
@@ -37,8 +37,8 @@ spec:
- metadata:
name: checkmate-mongo-persistent-storage
spec:
storageClassName: {{ .Values.persistence.mongo.storageClass | quote }}
storageClassName: "gp3"
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: {{ .Values.persistence.mongo.size | default "5Gi" | quote }}
storage: {{ .Values.persistence.mongodbSize }}
@@ -25,9 +25,9 @@ spec:
- metadata:
name: checkmate-redis-persistent-storage
spec:
storageClassName: {{ .Values.persistence.redis.storageClass | quote }}
storageClassName: "gp3"
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: {{ .Values.persistence.redis.size | default "1Gi" | quote }}
storage: {{ .Values.persistence.redisSize }}
{{- end }}
+2 -6
View File
@@ -44,9 +44,5 @@ secrets:
# REFRESH_TOKEN_TTL: 99d
persistence:
mongo:
size: 5Gi
storageClass: ""
redis:
size: 1Gi
storageClass: ""
mongodbSize: 5Gi
redisSize: 1Gi
+5 -22
View File
@@ -2,7 +2,6 @@ import { Stack, Typography } from "@mui/material";
import PropTypes from "prop-types";
import { useTheme } from "@emotion/react";
import Dot from "../Dot/index.jsx";
import { StatusLabel } from "@/Components/v1/Label/index.jsx";
/**
* Host component.
* This subcomponent receives a params object and displays the host details.
@@ -15,7 +14,7 @@ import { StatusLabel } from "@/Components/v1/Label/index.jsx";
* @param {number} params.percentage - The percentage to display.
* @returns {React.ElementType} Returns a div element with the host details.
*/
const Host = ({ url, title, percentageColor, percentage, showURL, status }) => {
const Host = ({ url, title, percentageColor, percentage, showURL }) => {
const theme = useTheme();
return (
<Stack>
@@ -23,36 +22,21 @@ const Host = ({ url, title, percentageColor, percentage, showURL, status }) => {
direction="row"
position="relative"
alignItems="center"
gap={theme.spacing(5)}
gap={theme.spacing(4)}
>
<Typography
variant="h6"
sx={{
fontWeight: 600,
}}
>
{title}
</Typography>
{title}
{percentageColor && percentage && (
<>
<Dot />
<Typography
variant="h6"
component="span"
sx={{
fontWeight: 600,
color: percentageColor,
fontWeight: 500,
}}
>
{percentage}%
</Typography>
{status && (
<StatusLabel
status={status}
text={status}
customStyles={{ textTransform: "capitalize" }}
/>
)}
</>
)}
</Stack>
@@ -67,7 +51,6 @@ Host.propTypes = {
percentage: PropTypes.string,
url: PropTypes.string,
showURL: PropTypes.bool,
status: PropTypes.string,
};
export default Host;
+4 -2
View File
@@ -147,9 +147,11 @@ const StatusLabel = ({ status, text, customStyles }) => {
}}
>
<Box
width={7}
height={7}
bgcolor={theme.palette[themeColor].lowContrast}
borderRadius="0%"
marginRight="1px"
borderRadius="50%"
marginRight="5px"
/>
</BaseLabel>
);
@@ -2,7 +2,7 @@ import Box from "@mui/material/Box";
import { BaseBox } from "@/Components/v2/DesignElements";
import type { MonitorStatus } from "@/Types/Monitor";
import { getStatusPalette } from "@/Utils/v2/MonitorUtils";
import { getStatusPalette } from "@/Utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
export const StatusLabel = ({
+1 -67
View File
@@ -1,8 +1,6 @@
import { Typography, Select } from "@mui/material";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import type { SelectProps } from "@mui/material/Select";
import { useTheme } from "@mui/material/styles";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
export const SelectInput: React.FC<SelectProps> = ({ ...props }) => {
const theme = useTheme();
@@ -22,67 +20,3 @@ export const SelectInput: React.FC<SelectProps> = ({ ...props }) => {
/>
);
};
type ItemTypes = string | number;
interface SelectItem {
_id: ItemTypes;
name: string;
}
export type CustomSelectProps = SelectProps & {
items: SelectItem[];
placeholder?: string;
isHidden?: boolean;
hasError?: boolean;
};
export const SelectFromItems: React.FC<CustomSelectProps> = ({
items,
placeholder,
isHidden = false,
hasError = false,
...props
}) => {
return (
<SelectInput
error={hasError}
IconComponent={KeyboardArrowDownIcon}
displayEmpty
MenuProps={{ disableScrollLock: true }}
renderValue={(selected) => {
if (!selected) {
return (
<Typography
noWrap
color="text.secondary"
>
{placeholder ?? ""}
</Typography>
);
}
const selectedItem = items.find((item) => item._id === selected);
const displayName = selectedItem ? selectedItem.name : placeholder;
return (
<Typography
noWrap
title={displayName}
>
{displayName}
</Typography>
);
}}
{...props}
>
{items.map((item) => (
<MenuItem
key={item._id}
value={item._id}
>
{item.name}
</MenuItem>
))}
</SelectInput>
);
};
SelectInput.displayName = "SelectInput";
SelectFromItems.displayName = "SelectFromItems";
@@ -4,7 +4,7 @@ import Typography from "@mui/material/Typography";
import AverageResponseIcon from "@/assets/icons/average-response-icon.svg?react";
import { Cell, RadialBarChart, RadialBar, ResponsiveContainer } from "recharts";
import { getResponseTimeColor } from "@/Utils/v2/MonitorUtils";
import { getResponseTimeColor } from "@/Utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
export const ChartAvgResponse = ({ avg, max }: { avg: number; max: number }) => {
@@ -1,7 +1,7 @@
import { BaseChart } from "./HistogramStatus";
import { BaseBox } from "../DesignElements";
import ResponseTimeIcon from "@/assets/icons/response-time-icon.svg?react";
import { normalizeResponseTimes } from "@/Utils/v2/DataUtils";
import { normalizeResponseTimes } from "@/Utils/DataUtils";
import {
AreaChart,
Area,
@@ -17,7 +17,7 @@ import {
formatDateWithTz,
tickDateFormatLookup,
tooltipDateFormatLookup,
} from "@/Utils/v2/TimeUtils";
} from "@/Utils/TimeUtils";
import { useTheme } from "@mui/material/styles";
import type { GroupedCheck } from "@/Types/Check";
import { useSelector } from "react-redux";
@@ -3,7 +3,7 @@ import Box from "@mui/material/Box";
import { useTheme } from "@mui/material/styles";
import type { Check } from "@/Types/Check";
import { HistogramResponseTimeTooltip } from "@/Components/v2/Monitors/HistogramResponseTimeTooltip";
import { normalizeResponseTimes } from "@/Utils/v2/DataUtils";
import { normalizeResponseTimes } from "@/Utils/DataUtils";
export const HistogramResponseTime = ({ checks }: { checks: Check[] }) => {
const normalChecks = normalizeResponseTimes(checks, "responseTime");
@@ -1,7 +1,7 @@
import Stack from "@mui/material/Stack";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { formatDateWithTz } from "@/Utils/v2/TimeUtils";
import { formatDateWithTz } from "@/Utils/TimeUtils";
import { useSelector } from "react-redux";
import type { LatestCheck } from "@/Types/Check";
@@ -9,12 +9,12 @@ import IncidentsIcon from "@/assets/icons/incidents.svg?react";
import type { GroupedCheck } from "@/Types/Check";
import type { MonitorStatus } from "@/Types/Monitor";
import { normalizeResponseTimes } from "@/Utils/v2/DataUtils";
import { normalizeResponseTimes } from "@/Utils/DataUtils";
import { useState } from "react";
import { formatDateWithTz } from "@/Utils/v2/TimeUtils";
import { formatDateWithTz } from "@/Utils/TimeUtils";
import { useSelector } from "react-redux";
import { useTheme } from "@mui/material/styles";
import { getResponseTimeColor } from "@/Utils/v2/MonitorUtils";
import { getResponseTimeColor } from "@/Utils/MonitorUtils";
const XLabel = ({
p1,
@@ -3,7 +3,7 @@ import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { PulseDot } from "@/Components/v2/DesignElements/PulseDot";
import { Dot } from "@/Components/v2/DesignElements/Dot";
import { getStatusColor, formatUrl } from "@/Utils/v2/MonitorUtils";
import { getStatusColor, formatUrl } from "@/Utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
import prettyMilliseconds from "pretty-ms";
import { typographyLevels } from "@/Utils/Theme/v2/palette";
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState } from "react";
import useSWR from "swr";
import type { SWRConfiguration } from "swr";
import type { AxiosRequestConfig } from "axios";
import { get, post, patch } from "@/Utils/v2/ApiClient"; // your axios wrapper
import { get, post, patch } from "@/Utils/ApiClient"; // your axios wrapper
export type ApiResponse = {
message: string;
@@ -1,17 +0,0 @@
import { monitorSchema } from "@/Validation/v2/zod";
import { z } from "zod";
export const useInitForm = ({
initialData,
}: {
initialData: Partial<z.infer<typeof monitorSchema>> | undefined;
}) => {
const defaults: z.infer<typeof monitorSchema> = {
type: initialData?.type || "http",
url: initialData?.url || "",
n: initialData?.n || 3,
notificationChannels: initialData?.notificationChannels || [],
name: initialData?.name || "",
interval: initialData?.interval || "1 minute",
};
return { defaults };
};
@@ -31,17 +31,14 @@ const useInfrastructureMonitorForm = () => {
[event.target.name]: event.target.checked,
});
};
const initializeInfrastructureMonitorForCreate = useCallback((globalSettings, monitorType = "hardware") => {
const initializeInfrastructureMonitorForCreate = useCallback((globalSettings) => {
const gt = globalSettings?.data?.settings?.globalThresholds || {};
// Docker monitors default to 30 seconds (0.5 minutes), hardware to 15 seconds (0.25 minutes)
const defaultInterval = monitorType === "docker" ? 0.5 : 0.25;
setInfrastructureMonitor((prev) => ({
...prev,
url: "",
name: "",
notifications: [],
interval: defaultInterval,
interval: 0.25,
cpu: gt.cpu !== undefined,
usage_cpu: gt.cpu !== undefined ? gt.cpu.toString() : "",
memory: gt.memory !== undefined,
@@ -5,7 +5,7 @@ import {
const useInfrastructureSubmit = () => {
const [createMonitor, isCreating] = useCreateMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const buildForm = (infrastructureMonitor, https, monitorType = "hardware") => {
const buildForm = (infrastructureMonitor, https) => {
const MS_PER_MINUTE = 60000;
let form = {
@@ -17,37 +17,31 @@ const useInfrastructureSubmit = () => {
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
statusWindowSize: infrastructureMonitor.statusWindowSize,
statusWindowThreshold: infrastructureMonitor.statusWindowThreshold,
cpu: infrastructureMonitor.cpu,
...(infrastructureMonitor.cpu
? { usage_cpu: infrastructureMonitor.usage_cpu }
: {}),
memory: infrastructureMonitor.memory,
...(infrastructureMonitor.memory
? { usage_memory: infrastructureMonitor.usage_memory }
: {}),
disk: infrastructureMonitor.disk,
...(infrastructureMonitor.disk
? { usage_disk: infrastructureMonitor.usage_disk }
: {}),
temperature: infrastructureMonitor.temperature,
...(infrastructureMonitor.temperature
? { usage_temperature: infrastructureMonitor.usage_temperature }
: {}),
secret: infrastructureMonitor.secret,
};
// Only add hardware-specific thresholds for hardware monitors
if (monitorType === "hardware") {
form.cpu = infrastructureMonitor.cpu;
if (infrastructureMonitor.cpu) {
form.usage_cpu = infrastructureMonitor.usage_cpu;
}
form.memory = infrastructureMonitor.memory;
if (infrastructureMonitor.memory) {
form.usage_memory = infrastructureMonitor.usage_memory;
}
form.disk = infrastructureMonitor.disk;
if (infrastructureMonitor.disk) {
form.usage_disk = infrastructureMonitor.usage_disk;
}
form.temperature = infrastructureMonitor.temperature;
if (infrastructureMonitor.temperature) {
form.usage_temperature = infrastructureMonitor.usage_temperature;
}
}
return form;
};
const submitInfrastructureForm = async (
infrastructureMonitor,
form,
isCreate,
monitorId,
monitorType = "hardware"
monitorId
) => {
const {
cpu,
@@ -61,24 +55,20 @@ const useInfrastructureSubmit = () => {
...rest
} = form;
// Only build thresholds for hardware monitors
const thresholds =
monitorType === "hardware"
? {
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
}
: {};
const thresholds = {
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
};
const finalForm = {
...(isCreate ? {} : { _id: monitorId }),
...rest,
description: form.name,
type: monitorType,
type: "hardware",
notifications: infrastructureMonitor.notifications,
...(Object.keys(thresholds).length > 0 ? { thresholds } : {}),
thresholds,
};
// Handle create or update
isCreate
@@ -13,7 +13,7 @@ import CustomAlertsSection from "./Components/CustomAlertsSection.jsx";
// Utils
import NotificationsConfig from "@/Components/v1/NotificationConfig/index.jsx";
import { useGetNotificationsByTeamId } from "../../../../Hooks/v1/useNotifications.js";
import { useParams, useSearchParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { useTheme } from "@emotion/react";
import { useTranslation } from "react-i18next";
@@ -29,7 +29,6 @@ import useInfrastructureSubmit from "./hooks/useInfrastructureSubmit.jsx";
const CreateInfrastructureMonitor = () => {
const { monitorId } = useParams();
const [searchParams] = useSearchParams();
const isCreate = typeof monitorId === "undefined";
const theme = useTheme();
@@ -44,11 +43,6 @@ const CreateInfrastructureMonitor = () => {
monitorId,
updateTrigger,
});
// Determine monitor type: from query params when creating, from monitor object when editing
const monitorType = isCreate
? (searchParams.get("type") || "hardware")
: (monitor?.type || "hardware");
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [globalSettings, globalSettingsLoading] = useFetchGlobalSettings();
const [notifications, notificationsAreLoading] = useGetNotificationsByTeamId();
@@ -65,7 +59,7 @@ const CreateInfrastructureMonitor = () => {
const { buildForm, submitInfrastructureForm, isCreating, isUpdating } =
useInfrastructureSubmit();
const ALL_FREQUENCIES = [
const FREQUENCIES = [
{ _id: 0.25, name: t("time.fifteenSeconds") },
{ _id: 0.5, name: t("time.thirtySeconds") },
{ _id: 1, name: t("time.oneMinute") },
@@ -73,12 +67,6 @@ const CreateInfrastructureMonitor = () => {
{ _id: 5, name: t("time.fiveMinutes") },
{ _id: 10, name: t("time.tenMinutes") },
];
// Docker monitors require minimum 30 second interval
const FREQUENCIES =
monitorType === "docker"
? ALL_FREQUENCIES.filter((f) => f._id >= 0.5)
: ALL_FREQUENCIES;
const CRUMBS = [
{ name: "Infrastructure monitors", path: "/infrastructure" },
...(isCreate
@@ -93,8 +81,7 @@ const CreateInfrastructureMonitor = () => {
if (isCreate) {
if (globalSettingsLoading) return;
setHttps(false);
const typeFromQuery = searchParams.get("type") || "hardware";
initializeInfrastructureMonitorForCreate(globalSettings, typeFromQuery);
initializeInfrastructureMonitorForCreate(globalSettings);
} else if (monitor) {
setHttps(monitor.url.startsWith("https"));
initializeInfrastructureMonitorForUpdate(monitor);
@@ -104,7 +91,6 @@ const CreateInfrastructureMonitor = () => {
monitor,
globalSettings,
globalSettingsLoading,
searchParams,
initializeInfrastructureMonitorForCreate,
initializeInfrastructureMonitorForUpdate,
]);
@@ -112,12 +98,12 @@ const CreateInfrastructureMonitor = () => {
// Handlers
const onSubmit = async (event) => {
event.preventDefault();
const form = buildForm(infrastructureMonitor, https, monitorType);
const form = buildForm(infrastructureMonitor, https);
const error = validateForm(form);
if (error) {
return;
}
submitInfrastructureForm(infrastructureMonitor, form, isCreate, monitorId, monitorType);
submitInfrastructureForm(infrastructureMonitor, form, isCreate, monitorId);
};
const triggerUpdate = () => {
@@ -214,25 +200,15 @@ const CreateInfrastructureMonitor = () => {
{t("settingsGeneralSettings")}
</Typography>
<Typography component="p">
{monitorType === "docker"
? "Configure your Capture server to monitor Docker containers."
: t("infrastructureCreateGeneralSettingsDescription")}
{t("infrastructureCreateGeneralSettingsDescription")}
</Typography>
<Typography component="p">
{monitorType === "docker" ? (
<>
Capture server endpoint: <code>/api/v1/metrics/docker</code>
</>
) : (
<>
{t("infrastructureServerRequirement")}{" "}
<Link
level="primary"
url="https://github.com/bluewave-labs/checkmate-agent"
label={t("common.monitoringAgentName")}
/>
</>
)}
{t("infrastructureServerRequirement")}{" "}
<Link
level="primary"
url="https://github.com/bluewave-labs/checkmate-agent"
label={t("common.monitoringAgentName")}
/>
</Typography>
</Stack>
<Stack gap={theme.spacing(8)}>
@@ -241,16 +217,8 @@ const CreateInfrastructureMonitor = () => {
id="url"
name="url"
startAdornment={<HttpAdornment https={https} />}
placeholder={
monitorType === "docker"
? "192.168.1.100:59232"
: "localhost:59232/api/v1/metrics"
}
label={
monitorType === "docker"
? "Capture Server URL"
: t("infrastructureServerUrlLabel")
}
placeholder={"localhost:59232/api/v1/metrics"}
label={t("infrastructureServerUrlLabel")}
https={https}
value={infrastructureMonitor.url}
onChange={onChange}
@@ -296,12 +264,7 @@ const CreateInfrastructureMonitor = () => {
type="text"
id="secret"
name="secret"
label={
monitorType === "docker"
? "Capture API Secret"
: t("infrastructureAuthorizationSecretLabel")
}
placeholder={monitorType === "docker" ? "Bearer token for Capture API" : ""}
label={t("infrastructureAuthorizationSecretLabel")}
value={infrastructureMonitor.secret}
onChange={onChange}
error={errors["secret"] ? true : false}
@@ -358,14 +321,12 @@ const CreateInfrastructureMonitor = () => {
/>
</Stack>
</ConfigBox>
{monitorType === "hardware" && (
<CustomAlertsSection
errors={errors}
onChange={onChange}
infrastructureMonitor={infrastructureMonitor}
handleCheckboxChange={handleCheckboxChange}
/>
)}
<CustomAlertsSection
errors={errors}
onChange={onChange}
infrastructureMonitor={infrastructureMonitor}
handleCheckboxChange={handleCheckboxChange}
/>
<ConfigBox>
<Box>
<Typography
@@ -1,267 +0,0 @@
import { Box, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react";
import PropTypes from "prop-types";
import DataTable from "@/Components/v1/Table/index.jsx";
import { StatusLabel } from "@/Components/v1/Label/index.jsx";
const DockerContainersTable = ({ containers = [], errors = [], captureVersion }) => {
const theme = useTheme();
// Helper to format uptime
const formatUptime = (startedAt, finishedAt, running) => {
if (!running && finishedAt > 0) {
const stoppedAgo = Math.floor(Date.now() / 1000) - finishedAt;
return formatDuration(stoppedAgo) + " ago";
}
if (running && startedAt > 0) {
const uptimeSeconds = Math.floor(Date.now() / 1000) - startedAt;
return formatDuration(uptimeSeconds);
}
return "N/A";
};
// Helper to format duration
const formatDuration = (seconds) => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days}d ${hours}h`;
if (hours > 0) return `${hours}h ${minutes}m`;
if (minutes > 0) return `${minutes}m`;
return `${seconds}s`;
};
// Helper to get status color
const getStatusColor = (status, running, healthy) => {
if (status === "running" && healthy) return "success";
if (status === "running" && !healthy) return "warning";
if (status === "exited") return "error";
if (status === "paused") return "warning";
if (status === "restarting") return "warning";
return "default";
};
const headers = [
{
id: "name",
content: "Container Name",
render: (row) => (
<Box>
<Typography
variant="body2"
fontWeight={600}
>
{row.container_name || "Unnamed"}
</Typography>
<Typography
variant="caption"
color={theme.palette.primary.contrastTextTertiary}
>
{row.container_id ? row.container_id.substring(0, 12) : "N/A"}
</Typography>
</Box>
),
},
{
id: "status",
content: "Status",
render: (row) => (
<StatusLabel
status={getStatusColor(row.status, row.running, row.health?.healthy)}
text={row.status || "unknown"}
/>
),
},
{
id: "health",
content: "Health",
render: (row) => (
<Box>
<Typography
variant="body2"
color={row.health?.healthy ? theme.palette.success.main : theme.palette.error.main}
>
{row.health?.healthy ? "Healthy" : "Unhealthy"}
</Typography>
<Typography
variant="caption"
color={theme.palette.primary.contrastTextTertiary}
>
{row.health?.source === "container_health_check" ? "HEALTHCHECK" : "State-based"}
</Typography>
</Box>
),
},
{
id: "image",
content: "Image",
render: (row) => (
<Typography variant="body2">{row.base_image || "N/A"}</Typography>
),
},
{
id: "uptime",
content: "Uptime",
render: (row) => (
<Typography variant="body2">
{formatUptime(row.started_at, row.finished_at, row.running)}
</Typography>
),
},
{
id: "ports",
content: "Ports",
render: (row) => (
<Box>
{row.exposed_ports && row.exposed_ports.length > 0 ? (
row.exposed_ports.map((port, idx) => (
<Typography
key={`${port.port}-${port.protocol}-${idx}`}
variant="caption"
sx={{ display: "block" }}
>
{port.port}/{port.protocol}
</Typography>
))
) : (
<Typography
variant="caption"
color={theme.palette.primary.contrastTextTertiary}
>
None
</Typography>
)}
</Box>
),
},
];
// Check if there are critical errors (Docker daemon down)
const dockerClientError = errors.find((e) => e.metric && e.metric.includes("docker.client"));
if (!containers || containers.length === 0) {
// Determine the message based on error type
let message = "No containers found";
let errorDetails = null;
if (dockerClientError) {
message = "Docker daemon unavailable";
errorDetails = dockerClientError.err;
} else if (errors && errors.length > 0) {
message = "Partial data available";
errorDetails = "Some containers could not be inspected";
}
return (
<Box
sx={{
padding: theme.spacing(12),
textAlign: "center",
border: dockerClientError
? `2px solid ${theme.palette.error.main}`
: `1px solid ${theme.palette.divider}`,
borderRadius: theme.spacing(2),
}}
>
<Typography
variant="body1"
color={dockerClientError ? theme.palette.error.main : theme.palette.primary.contrastTextTertiary}
fontWeight={600}
mb={errorDetails ? theme.spacing(2) : 0}
>
{message}
</Typography>
{errorDetails && (
<Typography
variant="body2"
color={theme.palette.primary.contrastTextSecondary}
>
{errorDetails}
</Typography>
)}
{captureVersion && (
<Typography
variant="caption"
color={theme.palette.primary.contrastTextTertiary}
sx={{ display: "block", marginTop: theme.spacing(4) }}
>
Capture version: {captureVersion}
</Typography>
)}
</Box>
);
}
return (
<Stack gap={theme.spacing(4)}>
<Box>
<Typography
variant="h3"
fontWeight={600}
>
Docker Containers ({containers.length})
</Typography>
{errors && errors.length > 0 && (
<Typography
variant="caption"
color={theme.palette.warning.main}
sx={{ display: "block", marginTop: theme.spacing(1) }}
>
⚠ {errors.length} error(s) encountered while fetching container data
</Typography>
)}
{captureVersion && (
<Typography
variant="caption"
color={theme.palette.primary.contrastTextTertiary}
sx={{ display: "block", marginTop: theme.spacing(1) }}
>
Capture version: {captureVersion}
</Typography>
)}
</Box>
<DataTable
headers={headers}
data={containers}
config={{
emptyView: "No containers found",
}}
/>
</Stack>
);
};
DockerContainersTable.propTypes = {
containers: PropTypes.arrayOf(
PropTypes.shape({
container_id: PropTypes.string,
container_name: PropTypes.string,
status: PropTypes.string,
health: PropTypes.shape({
healthy: PropTypes.bool,
source: PropTypes.string,
message: PropTypes.string,
}),
running: PropTypes.bool,
base_image: PropTypes.string,
exposed_ports: PropTypes.arrayOf(
PropTypes.shape({
port: PropTypes.string,
protocol: PropTypes.string,
})
),
started_at: PropTypes.number,
finished_at: PropTypes.number,
})
),
errors: PropTypes.arrayOf(
PropTypes.shape({
metric: PropTypes.arrayOf(PropTypes.string),
err: PropTypes.string,
})
),
captureVersion: PropTypes.string,
};
export default DockerContainersTable;
@@ -8,7 +8,6 @@ import GaugeBoxes from "./Components/GaugeBoxes/index.jsx";
import AreaChartBoxes from "./Components/AreaChartBoxes/index.jsx";
import GenericFallback from "@/Components/v1/GenericFallback/index.jsx";
import NetworkStats from "./Components/NetworkStats/index.jsx";
import DockerContainersTable from "./Components/DockerContainersTable/index.jsx";
import CustomTabList from "@/Components/v1/Tab/index.jsx";
import TabContext from "@mui/lab/TabContext";
@@ -99,27 +98,12 @@ const InfrastructureDetails = () => {
label={t("details")}
value="details"
/>
{monitor?.type !== "docker" && (
<Tab
label={t("network")}
value="network"
/>
)}
<Tab
label={t("network")}
value="network"
/>
</CustomTabList>
{tab === "details" && monitor?.type === "docker" && (
<>
<StatusBoxes
shouldRender={!isLoading}
monitor={monitor}
/>
<DockerContainersTable
containers={monitor?.stats?.aggregateData?.latestCheck?.docker || []}
errors={monitor?.stats?.aggregateData?.latestCheck?.errors || []}
captureVersion={monitor?.stats?.aggregateData?.latestCheck?.capture?.version}
/>
</>
)}
{tab === "details" && monitor?.type !== "docker" && (
{tab === "details" && (
<>
<StatusBoxes
shouldRender={!isLoading}
@@ -141,7 +125,7 @@ const InfrastructureDetails = () => {
/>
</>
)}
{tab === "network" && monitor?.type !== "docker" && (
{tab === "network" && (
<NetworkStats
net={monitor?.stats?.aggregateData?.latestCheck?.net || []}
isLoading={isLoading}
@@ -1,6 +1,5 @@
// Components
import { Stack, Tab } from "@mui/material";
import { TabContext, TabPanel } from "@mui/lab";
import { Stack } from "@mui/material";
import Breadcrumbs from "@/Components/v1/Breadcrumbs/index.jsx";
import MonitorCountHeader from "@/Components/v1/MonitorCountHeader/index.jsx";
import MonitorCreateHeader from "@/Components/v1/MonitorCreateHeader/index.jsx";
@@ -9,7 +8,6 @@ import Pagination from "@/Components/v1/Table/TablePagination/index.jsx";
import PageStateWrapper from "@/Components/v1/PageStateWrapper/index.jsx";
import Filter from "./Components/Filters/index.jsx";
import SearchComponent from "../../Uptime/Monitors/Components/SearchComponent/index.jsx";
import CustomTabList from "@/Components/v1/Tab/index.jsx";
// Utils
import { useTheme } from "@emotion/react";
import { useEffect, useState } from "react";
@@ -19,6 +17,7 @@ import { useFetchMonitorsByTeamId } from "../../../../Hooks/v1/monitorHooks.js";
import { useDispatch, useSelector } from "react-redux";
import { setRowsPerPage } from "../../../../Features/UI/uiSlice.js";
// Constants
const TYPES = ["hardware"];
const BREADCRUMBS = [{ name: `infrastructure`, path: "/infrastructure" }];
const InfrastructureMonitors = () => {
@@ -27,7 +26,6 @@ const InfrastructureMonitors = () => {
const dispatch = useDispatch();
// Local state
const [tab, setTab] = useState("hardware");
const [page, setPage] = useState(0);
const [updateTrigger, setUpdateTrigger] = useState(false);
const [selectedStatus, setSelectedStatus] = useState(undefined);
@@ -41,14 +39,6 @@ const InfrastructureMonitors = () => {
const { t } = useTranslation();
// Handlers
const handleTabChange = (event, newTab) => {
setTab(newTab);
setPage(0); // Reset to first page when changing tabs
setSearch(undefined); // Clear search
setSelectedStatus(undefined); // Clear filters
setToFilterStatus(undefined);
};
const handleActionMenuDelete = () => {
setUpdateTrigger(!updateTrigger);
};
@@ -80,12 +70,9 @@ const InfrastructureMonitors = () => {
const field = toFilterStatus !== undefined ? "status" : undefined;
// Determine monitor types based on active tab
const types = tab === "hardware" ? ["hardware"] : ["docker"];
const [monitors, summary, isLoading, networkError] = useFetchMonitorsByTeamId({
limit: 1,
types: types,
types: TYPES,
page,
field: field,
filter: toFilterStatus ?? search,
@@ -95,113 +82,55 @@ const InfrastructureMonitors = () => {
return (
<>
<Stack gap={theme.spacing(10)}>
<Breadcrumbs list={BREADCRUMBS} />
<MonitorCreateHeader
isAdmin={isAdmin}
isLoading={isLoading}
path={tab === "docker" ? "/infrastructure/create?type=docker" : "/infrastructure/create?type=hardware"}
/>
<TabContext value={tab}>
<CustomTabList value={tab} onChange={handleTabChange}>
<Tab label="Hardware" value="hardware" />
<Tab label="Docker Monitoring" value="docker" />
</CustomTabList>
<TabPanel value="hardware" sx={{ padding: 0 }}>
<PageStateWrapper
networkError={networkError}
<PageStateWrapper
networkError={networkError}
isLoading={isLoading}
items={monitors}
type="infrastructureMonitor"
fallbackLink="/infrastructure/create"
>
<Stack gap={theme.spacing(10)}>
<Breadcrumbs list={BREADCRUMBS} />
<MonitorCreateHeader
isAdmin={isAdmin}
isLoading={isLoading}
path="/infrastructure/create"
/>
<Stack direction={"row"}>
<MonitorCountHeader
isLoading={isLoading}
items={monitors}
type="infrastructureMonitor"
fallbackLink="/infrastructure/create?type=hardware"
>
<Stack gap={theme.spacing(10)}>
<Stack direction={"row"}>
<MonitorCountHeader
isLoading={isLoading}
monitorCount={summary?.totalMonitors ?? 0}
/>
<Filter
selectedStatus={selectedStatus}
setSelectedStatus={setSelectedStatus}
setToFilterStatus={setToFilterStatus}
handleReset={handleReset}
/>
<SearchComponent
monitors={monitors}
onSearchChange={setSearch}
setIsSearching={setIsSearching}
/>
</Stack>
monitorCount={summary?.totalMonitors ?? 0}
/>
<Filter
selectedStatus={selectedStatus}
setSelectedStatus={setSelectedStatus}
setToFilterStatus={setToFilterStatus}
handleReset={handleReset}
/>
<SearchComponent
monitors={monitors}
onSearchChange={setSearch}
setIsSearching={setIsSearching}
/>
</Stack>
<MonitorsTable
isLoading={isLoading}
monitors={monitors}
isAdmin={isAdmin}
handleActionMenuDelete={handleActionMenuDelete}
isSearching={isSearching}
/>
<Pagination
itemCount={summary?.totalMonitors}
paginationLabel={t("monitors")}
page={page}
rowsPerPage={rowsPerPage}
handleChangePage={handleChangePage}
handleChangeRowsPerPage={handleChangeRowsPerPage}
/>
</Stack>
</PageStateWrapper>
</TabPanel>
<TabPanel value="docker" sx={{ padding: 0 }}>
<PageStateWrapper
networkError={networkError}
isLoading={isLoading}
items={monitors}
type="infrastructureMonitor"
fallbackLink="/infrastructure/create?type=docker"
>
<Stack gap={theme.spacing(10)}>
<Stack direction={"row"}>
<MonitorCountHeader
isLoading={isLoading}
monitorCount={summary?.totalMonitors ?? 0}
/>
<Filter
selectedStatus={selectedStatus}
setSelectedStatus={setSelectedStatus}
setToFilterStatus={setToFilterStatus}
handleReset={handleReset}
/>
<SearchComponent
monitors={monitors}
onSearchChange={setSearch}
setIsSearching={setIsSearching}
/>
</Stack>
<MonitorsTable
isLoading={isLoading}
monitors={monitors}
isAdmin={isAdmin}
handleActionMenuDelete={handleActionMenuDelete}
isSearching={isSearching}
/>
<Pagination
itemCount={summary?.totalMonitors}
paginationLabel={t("monitors")}
page={page}
rowsPerPage={rowsPerPage}
handleChangePage={handleChangePage}
handleChangeRowsPerPage={handleChangeRowsPerPage}
/>
</Stack>
</PageStateWrapper>
</TabPanel>
</TabContext>
</Stack>
<MonitorsTable
isLoading={isLoading}
monitors={monitors}
isAdmin={isAdmin}
handleActionMenuDelete={handleActionMenuDelete}
isSearching={isSearching}
/>
<Pagination
itemCount={summary?.totalMonitors}
paginationLabel={t("monitors")}
page={page}
rowsPerPage={rowsPerPage}
handleChangePage={handleChangePage}
handleChangeRowsPerPage={handleChangeRowsPerPage}
/>
</Stack>
</PageStateWrapper>
</>
);
};
@@ -223,54 +223,18 @@ const CreateNotifications = () => {
<Typography component="p">{t(DESCRIPTION_MAP[type])}</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
{type === "matrix" ? (
<>
<TextInput
label={t("createNotifications.matrixSettings.homeserverLabel")}
name="homeserverUrl"
placeholder={t(
"createNotifications.matrixSettings.homeserverPlaceholder"
)}
value={notification.homeserverUrl || ""}
onChange={onChange}
error={Boolean(errors.homeserverUrl)}
helperText={errors["homeserverUrl"]}
/>
<TextInput
label={t("createNotifications.matrixSettings.roomIdLabel")}
name="roomId"
placeholder={t("createNotifications.matrixSettings.roomIdPlaceholder")}
value={notification.roomId || ""}
onChange={onChange}
error={Boolean(errors.roomId)}
helperText={errors["roomId"]}
/>
<TextInput
label={t("createNotifications.matrixSettings.accessTokenLabel")}
name="accessToken"
type="password"
placeholder={t(
"createNotifications.matrixSettings.accessTokenPlaceholder"
)}
value={notification.accessToken || ""}
onChange={onChange}
error={Boolean(errors.accessToken)}
helperText={errors["accessToken"]}
/>
</>
) : (
<TextInput
label={t(LABEL_MAP[type])}
name="address"
placeholder={t(PLACEHOLDER_MAP[type])}
value={notification.address}
onChange={onChange}
error={Boolean(errors.address)}
helperText={errors["address"]}
/>
)}
<TextInput
label={t(LABEL_MAP[type])}
name="address"
placeholder={t(PLACEHOLDER_MAP[type])}
value={notification.address}
onChange={onChange}
error={Boolean(errors.address)}
helperText={errors["address"]}
/>
</Stack>
</ConfigBox>{" "}
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
@@ -4,7 +4,6 @@ export const NOTIFICATION_TYPES = [
{ _id: 3, name: "PagerDuty", value: "pager_duty" },
{ _id: 4, name: "Webhook", value: "webhook" },
{ _id: 5, name: "Discord", value: "discord" },
{ _id: 6, name: "Matrix", value: "matrix" },
];
export const TITLE_MAP = {
@@ -13,7 +12,6 @@ export const TITLE_MAP = {
pager_duty: "createNotifications.pagerdutySettings.title",
webhook: "createNotifications.webhookSettings.title",
discord: "createNotifications.discordSettings.title",
matrix: "createNotifications.matrixSettings.title",
};
export const DESCRIPTION_MAP = {
@@ -22,7 +20,6 @@ export const DESCRIPTION_MAP = {
pager_duty: "createNotifications.pagerdutySettings.description",
webhook: "createNotifications.webhookSettings.description",
discord: "createNotifications.discordSettings.description",
matrix: "createNotifications.matrixSettings.description",
};
export const LABEL_MAP = {
@@ -31,7 +28,6 @@ export const LABEL_MAP = {
pager_duty: "createNotifications.pagerdutySettings.integrationKeyLabel",
webhook: "createNotifications.webhookSettings.webhookLabel",
discord: "createNotifications.discordSettings.webhookLabel",
matrix: "createNotifications.matrixSettings.homeserverLabel",
};
export const PLACEHOLDER_MAP = {
@@ -40,5 +36,4 @@ export const PLACEHOLDER_MAP = {
pager_duty: "createNotifications.pagerdutySettings.integrationKeyPlaceholder",
webhook: "createNotifications.webhookSettings.webhookPlaceholder",
discord: "createNotifications.discordSettings.webhookPlaceholder",
matrix: "createNotifications.matrixSettings.homeserverPlaceholder",
};
@@ -14,7 +14,7 @@ const useMonitorsFetch = () => {
try {
const response = await networkService.getMonitorsByTeamId({
limit: null, // donot return any checks for the monitors
types: ["http", "ping", "port", "game"], // include game servers in status page monitor selection
types: ["http", "ping", "port"], // status page is available for uptime, ping, and port monitors
});
setMonitors(response.data.data.monitors);
} catch (error) {
@@ -30,9 +30,7 @@ const MonitorsList = ({
<Stack
key={monitor._id}
width="100%"
gap={theme.spacing(10)}
margin="0 auto"
maxWidth="95%"
gap={theme.spacing(2)}
>
<Host
key={monitor._id}
@@ -41,18 +39,24 @@ const MonitorsList = ({
percentageColor={monitor.percentageColor}
percentage={monitor.percentage}
showURL={showURL}
status={status}
/>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(1)}
gap={theme.spacing(20)}
>
{statusPage.showCharts !== false && (
<Box flex={9}>
<StatusPageBarChart checks={monitor?.checks?.slice().reverse()} />
</Box>
)}
<Box flex={statusPage.showCharts !== false ? 1 : 10}>
<StatusLabel
status={status}
text={status}
customStyles={{ textTransform: "capitalize" }}
/>
</Box>
</Stack>
</Stack>
);
@@ -7,80 +7,6 @@ import { StatusLabel } from "@/Components/v1/Label/index.jsx";
import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "../../../../../../Utils/timeUtils.js";
import SkeletonLayout from "./skeleton.jsx";
import Tooltip from "@mui/material/Tooltip";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import { lighten, useTheme } from "@mui/material";
/**
* Creates tooltip content with detailed timing breakdown
* Following the pattern from IncidentTable's GetTooltip function
* @param {Object} timings - Timing object (guaranteed to have phases by caller)
* @param {Object} theme - MUI theme object
* @param {Function} t - Translation function
* @returns {JSX.Element} Tooltip content
*/
const GetTooltip = (timings, theme, t) => {
const phases = timings.phases;
const timingDetails = [
{ label: t("dnsLookup"), value: phases.dns },
{ label: t("tcpConnection"), value: phases.tcp },
{ label: t("tlsHandshake"), value: phases.tls },
{ label: t("waitTime"), value: phases.wait },
{ label: t("timeToFirstByte"), value: phases.firstByte },
{ label: t("download"), value: phases.download },
{ label: t("total"), value: phases.total },
].filter((item) => item.value > 0);
return (
<Stack
sx={{
py: theme.spacing(2),
px: theme.spacing(4),
}}
>
<Typography
variant="body2"
sx={{
fontWeight: 600,
marginBottom: theme.spacing(1),
color: theme.palette.primary.contrastText,
}}
>
{t("responseTimeBreakdown")}
</Typography>
{timingDetails.map((detail, index, array) => (
<Box
key={index}
sx={{
display: "flex",
justifyContent: "space-between",
gap: theme.spacing(4),
marginBottom: index < array.length - 1 ? theme.spacing(0.5) : 0,
}}
>
<Typography
variant="body2"
sx={{ color: theme.palette.primary.contrastText }}
>
{detail.label}:
</Typography>
<Typography
variant="body2"
sx={{
fontWeight: index === array.length - 1 ? 600 : 400,
color: theme.palette.primary.contrastText,
}}
>
{Math.round(detail.value)} ms
</Typography>
</Box>
))}
</Stack>
);
};
const ResponseTable = ({
isLoading = false,
checks = [],
@@ -92,8 +18,6 @@ const ResponseTable = ({
setRowsPerPage,
}) => {
const { t } = useTranslation();
const theme = useTheme();
if (isLoading) {
return <SkeletonLayout />;
}
@@ -130,56 +54,6 @@ const ResponseTable = ({
content: t("message"),
render: (row) => row.message,
},
{
id: "responseTime",
content: t("responseTime"),
render: (row) => {
const hasTimings = row.timings && row.timings.phases;
const responseTime = row.responseTime;
const responseTimeDisplay =
responseTime !== null && responseTime !== undefined
? `${Math.round(responseTime)} ms`
: "N/A";
if (!hasTimings) {
return responseTimeDisplay;
}
return (
<Tooltip
title={GetTooltip(row.timings, theme, t)}
placement="top"
arrow
enterDelay={300}
enterNextDelay={300}
slotProps={{
tooltip: {
sx: {
backgroundColor: lighten(theme.palette.primary.main, 0.1),
border: `1px solid ${theme.palette.primary.lowContrast}`,
borderRadius: theme.shape.borderRadius,
"& .MuiTooltip-arrow": {
color: lighten(theme.palette.primary.main, 0.1),
"&::before": {
border: `1px solid ${theme.palette.primary.lowContrast}`,
},
},
},
},
}}
>
<Box
sx={{
cursor: "help",
display: "inline-block",
}}
>
{responseTimeDisplay}
</Box>
</Tooltip>
);
},
},
];
return (
+1 -1
View File
@@ -10,7 +10,7 @@ import type { MonitorStatus } from "@/Types/Monitor";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useGet } from "@/Hooks/v2/UseApi";
import { formatDateWithTz } from "@/Utils/v2/TimeUtils";
import { formatDateWithTz } from "@/Utils/TimeUtils";
import { useSelector } from "react-redux";
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<Check>[] = [
-43
View File
@@ -1,43 +0,0 @@
import { monitorSchema } from "@/Validation/v2/zod";
import { useGet, usePost } from "@/Hooks/v2/UseApi";
import { UptimeForm } from "@/Pages/v2/Uptime/UptimeForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/Hooks/v2/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
export const UptimeConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & { interval: number | undefined };
const { id } = useParams();
const { response } = useGet<ApiResponse>("/notification-channels");
const { response: monitorResponse } = useGet<ApiResponse>(`/monitors/${id}`);
const monitor = monitorResponse?.data || null;
const notificationOptions = response?.data ?? [];
const { post, loading, error } = usePost<SubmitValues, ApiResponse>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
console.log(result);
} else {
console.error(error);
}
};
return (
<UptimeForm
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
+1 -1
View File
@@ -14,7 +14,7 @@ import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useGet, usePatch, type ApiResponse } from "@/Hooks/v2/UseApi";
import { useState } from "react";
import { getStatusPalette } from "@/Utils/v2/MonitorUtils";
import { getStatusPalette } from "@/Utils/MonitorUtils";
import prettyMilliseconds from "pretty-ms";
const UptimeDetailsPage = () => {
-247
View File
@@ -1,247 +0,0 @@
import Stack from "@mui/material/Stack";
import { TextInput } from "@/Components/v2/Inputs/TextInput";
import { AutoCompleteInput } from "@/Components/v2/Inputs/AutoComplete";
import { ConfigBox, BasePage } from "@/Components/v2/DesignElements";
import RadioGroup from "@mui/material/RadioGroup";
import FormControl from "@mui/material/FormControl";
import { RadioWithDescription } from "@/Components/v2/Inputs/RadioInput";
import { Button } from "@/Components/v2/Inputs";
import DeleteOutlineRoundedIcon from "@mui/icons-material/DeleteOutlineRounded";
import { Typography } from "@mui/material";
import { useTranslation } from "react-i18next";
import { monitorSchema } from "@/Validation/v2/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, Controller, useWatch, type SubmitHandler } from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/Hooks/v2/useInitMonitorForm";
type FormValues = z.infer<typeof monitorSchema>;
export const UptimeForm = ({
initialData,
onSubmit,
notificationOptions,
loading,
}: {
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const {
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
const selectedType = useWatch({
control,
name: "type",
});
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
return (
<BasePage
component={"form"}
onSubmit={handleSubmit(onSubmit)}
>
<ConfigBox
title={t("distributedUptimeCreateChecks")}
subtitle={t("distributedUptimeCreateChecksDescription")}
rightContent={
<Controller
name="type"
control={control}
render={({ field }) => (
<FormControl error={!!errors.type}>
<RadioGroup
{...field}
sx={{ gap: theme.spacing(6) }}
>
<RadioWithDescription
value="http"
label={"HTTP"}
description={"Use HTTP to monitor your website or API endpoint."}
/>
<RadioWithDescription
value="https"
label="HTTPS"
description="Use HTTPS to monitor your website or API endpoint.
"
/>
<RadioWithDescription
value="ping"
label={t("pingMonitoring")}
description={t("pingMonitoringDescription")}
/>
</RadioGroup>
</FormControl>
)}
/>
}
/>
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`uptimeGeneralInstructions.${selectedType}`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<Controller
name="url"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
label={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]} // important!
render={({ field }) => (
<AutoCompleteInput
multiple
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack
gap={theme.spacing(2)}
mt={theme.spacing(2)}
>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<DeleteOutlineRoundedIcon
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
sx={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
label={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
import type { MonitorStatus } from "@/Types/Monitor";
import type { PaletteKey } from "@/Utils/Theme/v2/theme";
import type { PaletteKey } from "./Theme/v2/theme";
export const getStatusPalette = (status: MonitorStatus): PaletteKey => {
const paletteMap: Record<MonitorStatus, PaletteKey> = {
up: "success",
File renamed without changes.
+1 -33
View File
@@ -458,7 +458,7 @@ const notificationValidation = joi.object({
type: joi
.string()
.valid("email", "webhook", "slack", "discord", "pager_duty", "matrix")
.valid("email", "webhook", "slack", "discord", "pager_duty")
.required()
.messages({
"string.empty": "Notification type is required",
@@ -495,40 +495,8 @@ const notificationValidation = joi.object({
"string.uri": "Please enter a valid Webhook URL",
}),
},
{
is: "matrix",
then: joi.string().allow("").optional(),
},
],
}),
homeserverUrl: joi.when("type", {
is: "matrix",
then: joi.string().uri().required().messages({
"string.empty": "Homeserver URL cannot be empty",
"any.required": "Homeserver URL is required",
"string.uri": "Please enter a valid Homeserver URL",
}),
otherwise: joi.string().allow("").optional(),
}),
roomId: joi.when("type", {
is: "matrix",
then: joi.string().required().messages({
"string.empty": "Room ID cannot be empty",
"any.required": "Room ID is required",
}),
otherwise: joi.string().allow("").optional(),
}),
accessToken: joi.when("type", {
is: "matrix",
then: joi.string().required().messages({
"string.empty": "Access Token cannot be empty",
"any.required": "Access Token is required",
}),
otherwise: joi.string().allow("").optional(),
}),
});
const editUserValidation = joi.object({
+17
View File
@@ -15,11 +15,15 @@ html {
-moz-osx-font-smoothing: grayscale;
/* Generalized Stylings */
--env-var-radius-1: 4px;
--env-var-radius-2: 8px;
--env-var-width-1: 100vw;
--env-var-width-2: 360px;
--env-var-width-3: 250px;
--env-var-width-4: 100px;
--env-var-height-1: 100vh;
--env-var-height-2: 34px;
--env-var-nav-bar-height: 70px;
@@ -31,6 +35,9 @@ html {
--env-var-spacing-1-plus: 16px;
--env-var-spacing-1-minus: 10px;
--env-var-spacing-2: 24px;
--env-var-spacing-3: 32px;
--env-var-spacing-4: 40px;
--env-var-spacing-5: 65px;
--env-var-font-size-small: 11px;
--env-var-font-size-small-plus: 12px;
@@ -39,6 +46,16 @@ html {
--env-var-font-size-large: 16px;
--env-var-font-size-large-plus: 22px;
--env-var-font-size-xlarge: 30px;
--env-var-img-width-1: 20px;
--env-var-img-width-2: 16px;
--env-var-img-width-3: 12px;
--env-var-default-1: 24px;
--env-var-default-2: 40px;
--env-var-shadow-1:
0px 4px 24px -4px rgba(16, 24, 40, 0.08), 0px 3px 3px -3px rgba(16, 24, 40, 0.03);
}
.MuiInputBase-root.Mui-disabled input {
+3 -14
View File
@@ -421,13 +421,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "",
@@ -489,8 +483,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "",
@@ -1078,11 +1071,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -421,13 +421,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "",
@@ -489,8 +483,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1078,11 +1071,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+83 -94
View File
@@ -382,56 +382,50 @@
"created": "Angelegt"
},
"addTeamMember": {
"addMemberMenu": "Teammitglied hinzufügen",
"title": "Neues Teammitglied registrieren",
"description": "Einen neuen Benutzer anlegen und Zugangsdaten mit ihm teilen. Diese Methode gibt dem Mitglied direkt Zugriff auf alle Überwachungen.",
"addButton": "Mitglied hinzufügen"
"addMemberMenu": "",
"title": "",
"description": "",
"addButton": ""
},
"register": "Teammitglied registrieren",
"register": "",
"registerToast": {
"success": "Benutzer erstellt, Zugangsdaten auf sichere Weise weitergeben.",
"dbUserExists": "Der Benutzer existiert bereits.",
"unknownError": "Unbekannter Fehler aufgetreten."
"success": "",
"dbUserExists": "",
"unknownError": ""
},
"registerTeamMember": {
"title": "Teammitglied registrieren",
"title": "",
"auth": {
"common": {
"inputs": {
"firstName": {
"errors": {
"empty": "Bitte einen Namen eingeben",
"pattern": "Der Name darf nur Buchstaben, Leerzeichen, Apostrophe oder Bindestriche enthalten"
"empty": "",
"pattern": ""
}
},
"lastName": {
"errors": {
"empty": "Bitte einen Vornamen eingeben",
"pattern": "Der Vorname darf nur Buchstaben, Leerzeichen, Apostrophe oder Bindestriche enthalten"
"empty": "",
"pattern": ""
}
},
"email": {
"errors": {
"empty": "Zum Fortsetzen bitte eine E-Mail-Adresse eingeben",
"invalid": "Bitte die Gültigkeit der E-Mail-Adresse erneut prüfen"
"empty": "",
"invalid": ""
}
},
"role": {
"errors": {
"empty": "Eine Rolle wird benötigt"
"empty": ""
}
}
}
}
}
},
"role": "Rolle",
"changeTeamPassword": {
"changePasswordMenu": "Passwort zurücksetzen",
"title": "Passwort des Teammitgliedes zurücksetzen",
"description": "Neues Passwort für dieses Teammitglied erstellen. Es muss auf einem Sicheren weg zur Verfügung gestellt werden.",
"success": "Passwort erfolgreich zurückgesetzt. Bitte sicherstellen, dass die Zugangsdaten auf sichere Weise weitergegeben werden."
}
"role": ""
},
"monitorState": {
"paused": "Pausiert",
@@ -493,8 +487,7 @@
"ping": "Geben Sie die IP-Adresse oder den Hostnamen ein, der angepingt werden soll (z. B. 192.168.1.100 oder example.com), und fügen Sie einen eindeutigen Anzeigenamen hinzu, der auf dem Dashboard angezeigt wird.",
"docker": "Geben Sie die Docker-ID Ihres Containers ein. Docker-IDs müssen die vollständige 64-Zeichen-ID sein. Sie können docker inspect <short_id> ausführen, um die vollständige Container-ID abzurufen.",
"port": "Geben Sie die URL oder IP des Servers, die Portnummer und einen eindeutigen Anzeigenamen ein, der auf dem Dashboard angezeigt wird.",
"game": "IP Adresse oder Hostnamen und Port für Ping eingeben (z.B. 192.168.1.100 oder beispiel.de) und Spieletyp auswählen.",
"https": "Zu überwachende Adresse oder IP (z.B. https://beispiel.de/ oder 192.168.1.100) eingeben und einen klaren Anzeigenamen, der im Dashboard erscheint."
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -614,7 +607,7 @@
"forgotPassword": "Passwort vergessen?",
"register": "Noch keinen Account?",
"forgotPasswordLink": "Passwort zurücksetzen",
"registerLink": "Hier registrieren"
"registerLink": "Hier resistrieren"
},
"toasts": {
"success": "Willkommen zurück. Erfolgreich angemeldet.",
@@ -625,7 +618,7 @@
"incorrect": "Das Passwort stimmt nicht mit dem gespeicherten überein"
}
},
"welcome": "Willkommen zurück bei Checkmate!"
"welcome": ""
},
"registration": {
"heading": {
@@ -652,7 +645,7 @@
"toasts": {
"success": "Willkommen! Benutzer erfolgreich angelegt"
},
"welcome": "Willkommen bei Checkmate!"
"welcome": ""
},
"forgotPassword": {
"heading": "Passwort vergessen?",
@@ -753,8 +746,8 @@
"monitorStatus": {
"checkingEvery": "Überprüfung alle {{interval}}",
"withCaptureAgent": "mit Capture-Agent {{version}}",
"up": "Online",
"down": "Offline",
"up": "hoch",
"down": "runter",
"paused": "pausiert"
},
"advancedMatching": "Erweiterter Abgleich",
@@ -799,7 +792,7 @@
"lastRunHeader": "Letzter Lauf um",
"lastFinishedAtHeader": "Zuletzt abgeschlossen um",
"lastRunTookHeader": "Letzter Lauf dauerte",
"intervalHeader": "Invervall"
"intervalHeader": ""
},
"metricsTable": {
"title": "Warteschlangenmetriken",
@@ -907,8 +900,8 @@
"title": "Überwachen Sie IP/URL auf der Statusseite"
},
"globalThresholds": {
"title": "Globale Schwellenwerte",
"description": "Globale CPU-, Speicher-, Festplatten- und Temperaturschwellenwerte festlegen. Wenn ein Wert angegeben ist, wird er automatisch für die Überwachung genutzt."
"title": "",
"description": ""
}
},
"statusPageCreate": {
@@ -982,11 +975,11 @@
"oneHour": "1 Stunde",
"oneDay": "1 Tag",
"oneWeek": "1 Woche",
"fourMinutes": "4 Minuten",
"oneMinute": "Eine Minute",
"twoMinutes": "Zwei Minuten",
"fifteenSeconds": "15 Sekunden",
"thirtySeconds": "30 Sekunden"
"fourMinutes": "",
"oneMinute": "",
"twoMinutes": "",
"fifteenSeconds": "",
"thirtySeconds": ""
},
"general": {
"noOptionsFound": "Keine {{unit}} gefunden"
@@ -1057,77 +1050,73 @@
"incidentsPageActionResolveMonitor": "Monitor-Vorfälle beheben",
"incidentsPageActionResolveAll": "Alle Vorfälle lösen",
"matchMethodOptions": {
"equal": "Gleich",
"equalPlaceholder": "Erfolg",
"include": "Enthält",
"includePlaceholder": "OK",
"regex": "Regex",
"regexPlaceholder": "^(success|ok)$",
"text": "Übereinstummungsmethode"
"equal": "",
"equalPlaceholder": "",
"include": "",
"includePlaceholder": "",
"regex": "",
"regexPlaceholder": "",
"text": ""
},
"monitorType": {
"docker": {
"label": "Container Name/ID",
"namePlaceholder": "Mein Container",
"placeholder": "Meine-App"
"label": "",
"namePlaceholder": "",
"placeholder": ""
},
"http": {
"label": "Zu überwachende URL",
"namePlaceholder": "Google",
"placeholder": "google.de"
"label": "",
"namePlaceholder": "",
"placeholder": ""
},
"ping": {
"label": "Zu überwachende IP-Adresse",
"namePlaceholder": "Google",
"placeholder": "1.1.1.1"
"label": "",
"namePlaceholder": "",
"placeholder": ""
},
"port": {
"label": "Zu überwachende URL",
"namePlaceholder": "localhost:5173",
"placeholder": "localhost"
"label": "",
"namePlaceholder": "",
"placeholder": ""
},
"game": {
"label": "Zu überwachende URL",
"namePlaceholder": "localhost:5173",
"placeholder": "localhost"
"label": "",
"namePlaceholder": "",
"placeholder": ""
}
},
"uptimeAdvancedMatching": {
"jsonPath": "JSON Pfad"
"jsonPath": ""
},
"bytesPerSecond": "Bytes pro Sekunde",
"bytesReceived": "Empfangene Bytes",
"bytesSent": "Gesendete Bytes",
"chooseGame": "Spiel auswählen",
"bytesPerSecond": "",
"bytesReceived": "",
"bytesSent": "",
"chooseGame": "",
"createMonitorPage": {
"incidentConfigDescription": "Mithilfe eines gleitenden Fensters wird ermittelt, wann ein Monitor ausfällt. Der Status eines Monitors ändert sich nur, wenn der Prozentsatz der Prüfungen im gleitenden Fenster den angegebenen Wert erreicht.",
"incidentConfigStatusWindowLabel": "Wie viele Prüfungen sollen im gleitenden Fenster ausgeführt werden?",
"incidentConfigStatusWindowThresholdLabel": "Wie viel Prozent der Prüfungen im gleitenden Fenster sollen fehlschlagen/erfolgreich sein, bevor sich der Status ändert?",
"incidentConfigTitle": "Vorfälle",
"incidentConfigDescriptionV2": "Anzahl der aufeinanderfolgenden Prüfungen, die zum Ändern des Monitorstatus erforderlich sind. Maximal 25",
"incidentConfigStatusCheckNumber": "Anzahl der Prüfungen bevor sich er Status ändert",
"intervalTitle": "Prüfintervall",
"intervalDescription": "Wie oft soll die Überwachung geprüft werden."
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": ""
},
"dataRate": "Datenrate",
"dataReceived": "Empfangene Daten",
"dataSent": "Gesendete Daten",
"details": "Details",
"drops": "verloren",
"errors": "Fehler",
"errorsIn": "Fehler eingehend",
"errorsOut": "Fehler ausgehend",
"gameServerMonitoring": "Spiele Server Überwachung",
"gameServerMonitoringDescription": "Prüfen ob der Spiele-Server läuft oder nicht",
"network": "Netzwerk",
"networkDrops": "Netzwerkabbrüche",
"networkErrors": "Netzwerkfehler",
"networkInterface": "Netzwerkschnittstelle",
"noNetworkStatsAvailable": "Keine Netzwerkstatistiken verfügbar.",
"packetsPerSecond": "Pakete pro Sekunde",
"packetsReceived": "Empfangene Pakete",
"packetsReceivedRate": "Rate empfangener Pakete",
"packetsSent": "Gesendete Pakete",
"rate": "Rate",
"selectInterface": "Schnittstelle auswählen"
"dataRate": "",
"dataReceived": "",
"dataSent": "",
"details": "",
"drops": "",
"errors": "",
"errorsIn": "",
"errorsOut": "",
"gameServerMonitoring": "",
"gameServerMonitoringDescription": "",
"network": "",
"networkDrops": "",
"networkErrors": "",
"networkInterface": "",
"noNetworkStatsAvailable": "",
"packetsPerSecond": "",
"packetsReceived": "",
"packetsReceivedRate": "",
"packetsSent": "",
"rate": "",
"selectInterface": ""
}
+4 -11
View File
@@ -20,13 +20,6 @@
"delete": "Delete",
"configure": "Configure",
"responseTime": "Response time",
"responseTimeBreakdown": "Response time breakdown",
"dnsLookup": "DNS lookup",
"tcpConnection": "TCP connection",
"tlsHandshake": "TLS handshake",
"waitTime": "Wait time",
"timeToFirstByte": "Time to first byte",
"download": "Download",
"ms": "ms",
"bar": "Bar",
"area": "Area",
@@ -497,11 +490,11 @@
},
"uptimeGeneralInstructions": {
"http": "Enter the URL or IP to monitor (e.g., https://example.com/ or 192.168.1.100) and add a clear display name that appears on the dashboard.",
"https": "Enter the URL or IP to monitor (e.g., https://example.com/ or 192.168.1.100) and add a clear display name that appears on the dashboard.",
"ping": "Enter the IP address or hostname to ping (e.g., 192.168.1.100 or example.com) and add a clear display name that appears on the dashboard.",
"docker": "Enter the Docker container name or ID. You can use either the container name (e.g., my-app) or the container ID (full 64-char ID or short ID).",
"port": "Enter the URL or IP of the server, the port number and a clear display name that appears on the dashboard.",
"game": "Enter the IP address or hostname and the port number to ping (e.g., 192.168.1.100 or example.com) and choose game type.",
"https": "Enter the URL or IP to monitor (e.g., https://example.com/ or 192.168.1.100) and add a clear display name that appears on the dashboard."
"game": "Enter the IP address or hostname and the port number to ping (e.g., 192.168.1.100 or example.com) and choose game type."
},
"common": {
"appName": "Checkmate",
@@ -1108,11 +1101,11 @@
"chooseGame": "Choose game",
"createMonitorPage": {
"incidentConfigDescription": "A sliding window is used to determine when a monitor goes down. The status of a monitor will only change when the percentage of checks in the sliding window meet the specified value.",
"incidentConfigDescriptionV2": "Number of consecutive checks needed to change monitor status. Maximum 25",
"incidentConfigStatusWindowLabel": "How many checks should be in the sliding window?",
"incidentConfigStatusCheckNumber": "How many checks before status change?",
"incidentConfigStatusWindowThresholdLabel": "What percentage of checks in the sliding window fail/succeed before monitor status changes?",
"incidentConfigTitle": "Incidents",
"incidentConfigDescriptionV2": "Number of consecutive checks needed to change monitor status. Maximum 25",
"incidentConfigStatusCheckNumber": "How many checks before status change?",
"intervalTitle": "Check interval",
"intervalDescription": "How often the monitor should be checked."
},
+36 -47
View File
@@ -129,32 +129,32 @@
"distributedUptimeStatusPublishedLabel": "",
"distributedUptimeStatusCompanyNameLabel": "",
"distributedUptimeStatusPageAddressLabel": "",
"distributedUptimeStatus30Days": "30 dias",
"distributedUptimeStatus60Days": "60 días",
"distributedUptimeStatus90Days": "90 dias",
"distributedUptimeStatus30Days": "",
"distributedUptimeStatus60Days": "",
"distributedUptimeStatus90Days": "",
"distributedUptimeStatusPageNotSetUp": "",
"distributedUptimeStatusContactAdmin": "",
"distributedUptimeStatusPageNotPublic": "",
"distributedUptimeStatusPageDeleteDialog": "",
"distributedUptimeStatusPageDeleteConfirm": "",
"distributedUptimeStatusPageDeleteDescription": "",
"distributedUptimeStatusDevices": "Dispositivos",
"distributedUptimeStatusDevices": "",
"distributedUptimeStatusUpt": "",
"distributedUptimeStatusUptBurned": "",
"distributedUptimeStatusUptLogo": "",
"incidentsTableNoIncidents": "",
"incidentsTablePaginationLabel": "Incidentes",
"incidentsTablePaginationLabel": "",
"incidentsTableMonitorName": "",
"incidentsTableStatus": "Estado",
"incidentsTableStatus": "",
"incidentsTableDateTime": "",
"incidentsTableStatusCode": "",
"incidentsTableMessage": "Mensaje",
"incidentsTableMessage": "",
"incidentsOptionsHeader": "",
"incidentsOptionsHeaderFilterBy": "",
"incidentsOptionsHeaderFilterAll": "Todo",
"incidentsOptionsHeaderFilterAll": "",
"incidentsOptionsHeaderFilterDown": "",
"incidentsOptionsHeaderFilterCannotResolve": "",
"incidentsOptionsHeaderShow": "Mostrar:",
"incidentsOptionsHeaderShow": "",
"incidentsOptionsHeaderLastHour": "",
"incidentsOptionsHeaderLastDay": "",
"incidentsOptionsHeaderLastWeek": "",
@@ -165,22 +165,22 @@
"infrastructureCustomizeAlerts": "",
"infrastructureAlertNotificationDescription": "",
"infrastructureCreateMonitor": "",
"infrastructureProtocol": "Protocolo",
"infrastructureProtocol": "",
"infrastructureServerUrlLabel": "",
"infrastructureDisplayNameLabel": "",
"infrastructureAuthorizationSecretLabel": "",
"gb": "GB",
"mb": "MB",
"mem": "Mem",
"gb": "",
"mb": "",
"mem": "",
"memoryUsage": "",
"cpu": "CPU",
"cpu": "",
"cpuUsage": "",
"cpuTemperature": "",
"diskUsage": "",
"used": "",
"total": "Total",
"cores": "Nucleos",
"frequency": "Frecuencia",
"total": "",
"cores": "",
"frequency": "",
"status": "",
"cpuPhysical": "",
"cpuLogical": "",
@@ -189,25 +189,25 @@
"memory": "",
"disk": "",
"uptime": "",
"os": "SO",
"os": "",
"host": "",
"actions": "",
"integrations": "",
"integrationsPrism": "",
"integrationsSlack": "Slack",
"integrationsSlack": "",
"integrationsSlackInfo": "",
"integrationsDiscord": "Discord",
"integrationsDiscord": "",
"integrationsDiscordInfo": "",
"integrationsZapier": "Zapier",
"integrationsZapier": "",
"integrationsZapierInfo": "",
"commonSave": "Guardar",
"commonSave": "",
"createYour": "",
"createMonitor": "",
"pause": "Pausar",
"resume": "Resumir",
"editing": "Editando...",
"url": "URL",
"access": "Acceso",
"pause": "",
"resume": "",
"editing": "",
"url": "",
"access": "",
"timezone": "",
"features": "",
"administrator": "",
@@ -231,13 +231,13 @@
"friendlyNamePlaceholder": "",
"maintenanceRepeat": "",
"maintenance": "",
"duration": "Duración",
"duration": "",
"addMonitors": "",
"window": "ventana",
"cancel": "Cancelar",
"message": "Mensaje",
"low": "bajo",
"high": "alto",
"window": "",
"cancel": "",
"message": "",
"low": "",
"high": "",
"statusCode": "",
"date&Time": "",
"type": "",
@@ -421,13 +421,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "",
@@ -489,8 +483,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "",
@@ -1078,11 +1071,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -421,13 +421,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "Tauota",
@@ -489,8 +483,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "",
@@ -1078,11 +1071,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "Pause",
@@ -493,8 +487,7 @@
"ping": "Entrez l'adresse IP ou le nom d'hôte à tester (par exemple, 192.168.1.100 ou exemple.fr) et ajoutez un nom familier qui apparaîtra sur le tableau de bord.",
"docker": "Entrer l'ID Docker du container. Les identifiants Docker doivent être les 64 caractères de l'ID Docker. Vous pouvez utiliser la commande docker inspect <short_id> pour avoir l'ID complet.",
"port": "Entrez l'URL ou l'adresse IP du serveur, le numéro de port et un nom d'affichage familier qui apparaîtra sur le tableau de bord.",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1103,11 +1096,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "一時停止",
@@ -493,8 +487,7 @@
"ping": "pingするIPアドレスまたはホスト名を入力(例: 192.168.1.100 または example.com)し、ダッシュボードに表示される明確な表示名を追加。",
"docker": "コンテナのDocker IDを入力。Docker IDは64文字のフルDocker IDである必要があります。docker inspect <short_id>を実行してフルコンテナIDを取得できます。",
"port": "サーバーのURLまたはIP、ポート番号、ダッシュボードに表示される明確な表示名を入力。",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1082,11 +1075,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "Pausado",
@@ -493,8 +487,7 @@
"ping": "Insira o endereço IP ou nome de domínio para ping (ex. 192.168.1.100 ou exemplo.com.br) e adicione uma descrição que aparecerá na dashboard.",
"docker": "Insira o Docker Id do seu container. Docker Ids devem ser todos os 64 caracteres. Você pode executar docker inspect <short_id> para descobrir o Id completo.",
"port": "Insira a URL ou o IP do servidor, aporta e uma descrição que aparecerá na dashboard.",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1103,11 +1096,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+351 -387
View File
File diff suppressed because it is too large. Load diff
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "บทบาท",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": "บทบาท"
},
"monitorState": {
"paused": "หยุดชั่วคราว",
@@ -493,8 +487,7 @@
"ping": "กรอกที่อยู่ IP หรือชื่อโฮสต์ที่ต้องการ ping (เช่น 192.168.1.100 หรือ example.com) และตั้งชื่อที่ชัดเจนให้แสดงบนแดชบอร์ด",
"docker": "กรอกชื่อหรือ ID ของคอนเทนเนอร์ Docker คุณสามารถใช้ชื่อคอนเทนเนอร์ (เช่น my-app) หรือ ID ของคอนเทนเนอร์ (ID เต็ม 64 ตัวอักษร หรือ ID สั้น)",
"port": "กรอก URL หรือ IP ของเซิร์ฟเวอร์ หมายเลขพอร์ต และตั้งชื่อที่ชัดเจนให้แสดงบนแดชบอร์ด",
"game": "กรอกที่อยู่ IP หรือชื่อโฮสต์และหมายเลขพอร์ตเพื่อทำการ ping (เช่น 192.168.1.100 หรือ example.com) และเลือกประเภทเกม",
"https": ""
"game": "กรอกที่อยู่ IP หรือชื่อโฮสต์และหมายเลขพอร์ตเพื่อทำการ ping (เช่น 192.168.1.100 หรือ example.com) และเลือกประเภทเกม"
},
"common": {
"appName": "Checkmate",
@@ -1103,11 +1096,7 @@
"incidentConfigDescription": "การใช้หน้าต่างเลื่อนจะช่วยกำหนดเวลาที่ตัวตรวจสอบล้มเหลว สถานะของตัวตรวจสอบจะเปลี่ยนก็ต่อเมื่อเปอร์เซ็นต์ของการตรวจสอบในหน้าต่างเลื่อนตรงตามค่าที่กำหนด",
"incidentConfigStatusWindowLabel": "ต้องมีการตรวจสอบกี่ครั้งในหน้าต่างเลื่อน?",
"incidentConfigStatusWindowThresholdLabel": "ต้องการให้กี่เปอร์เซ็นต์ของการตรวจสอบในหน้าต่างเลื่อนล้มเหลว/สำเร็จ ก่อนที่จะเปลี่ยนสถานะของตัวตรวจสอบ?",
"incidentConfigTitle": "เหตุการณ์",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": "เหตุการณ์"
},
"dataRate": "อัตราการส่งข้อมูล",
"dataReceived": "ข้อมูลที่รับ",
+3 -14
View File
@@ -421,13 +421,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "Durduruldu",
@@ -489,8 +483,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1078,11 +1071,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "角色",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": "角色"
},
"monitorState": {
"paused": "暂停",
@@ -493,8 +487,7 @@
"ping": "输入要 ping 的 IP 地址或主机名(例如.. 192.168.1.100 或 example.com),并添加显示在仪表板上的清晰显示名称。",
"docker": "码输入 Docker 容器名称或 ID。您可以使用容器名称(例如.. my-app)或容器 ID(完整的 64 字符 ID 或短 ID)。",
"port": "输入服务器的 URL 或 IP、端口号和仪表板上显示的清晰显示名称。",
"game": "输入要 ping 的 IP 地址或主机名和端口号(例如.. 192.168.1.100 或 example.com)并选择游戏类型。",
"https": ""
"game": "输入要 ping 的 IP 地址或主机名和端口号(例如.. 192.168.1.100 或 example.com)并选择游戏类型。"
},
"common": {
"appName": "Checkmate",
@@ -1095,11 +1088,7 @@
"incidentConfigDescription": "滑动窗口用于确定监视器何时发生故障。仅当滑动窗口中的检查百分比满足指定值时,监视器的状态才会改变。",
"incidentConfigStatusWindowLabel": "在滑动窗口中应包含多少次检测?",
"incidentConfigStatusWindowThresholdLabel": "在监视器状态改变之前,滑动窗口中的检查失败/成功的百分比是多少?",
"incidentConfigTitle": "事件",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": "事件"
},
"dataRate": "数据速率",
"dataReceived": "已接收数据",
+3 -14
View File
@@ -425,13 +425,7 @@
}
}
},
"role": "",
"changeTeamPassword": {
"changePasswordMenu": "",
"title": "",
"description": "",
"success": ""
}
"role": ""
},
"monitorState": {
"paused": "",
@@ -493,8 +487,7 @@
"ping": "",
"docker": "",
"port": "",
"game": "",
"https": ""
"game": ""
},
"common": {
"appName": "Checkmate",
@@ -1082,11 +1075,7 @@
"incidentConfigDescription": "",
"incidentConfigStatusWindowLabel": "",
"incidentConfigStatusWindowThresholdLabel": "",
"incidentConfigTitle": "",
"incidentConfigDescriptionV2": "",
"incidentConfigStatusCheckNumber": "",
"intervalTitle": "",
"intervalDescription": ""
"incidentConfigTitle": ""
},
"dataRate": "",
"dataReceived": "",
+1 -1
View File
@@ -7,7 +7,7 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default defineConfig(({}) => {
let version = "3.2.1";
let version = "3.2.0";
return {
base: "/",
+1153 -1274
View File
File diff suppressed because it is too large. Load diff
+4 -7
View File
@@ -6,8 +6,8 @@
"type": "module",
"scripts": {
"test": "c8 mocha",
"dev": "tsx watch src/index.js",
"start": "node --watch ./dist/index.js",
"dev": "nodemon --exec tsx src/index.js",
"start": "nodemon ./dist/index.js",
"build": "tsc",
"lint": "eslint .",
"lint-fix": "eslint --fix .",
@@ -17,15 +17,11 @@
"keywords": [],
"author": "",
"license": "ISC",
"engines": {
"node": ">=20"
},
"dependencies": {
"@pulsecron/pulse": "1.6.8",
"axios": "^1.7.2",
"bcryptjs": "3.0.2",
"bullmq": "5.41.2",
"cacheable-lookup": "7.0.0",
"compression": "1.8.1",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
@@ -52,7 +48,7 @@
"ping": "0.4.4",
"sharp": "0.33.5",
"ssl-checker": "2.0.10",
"super-simple-scheduler": "1.4.5",
"super-simple-scheduler": "1.4.1",
"swagger-ui-express": "5.0.1",
"winston": "^3.13.0"
},
@@ -69,6 +65,7 @@
"esm": "3.2.25",
"globals": "^15.14.0",
"mocha": "11.1.0",
"nodemon": "3.1.9",
"prettier": "^3.3.3",
"sinon": "19.0.2",
"tsx": "4.20.5",
@@ -452,24 +452,6 @@ class MonitorController extends BaseController {
SERVICE_NAME,
"getAllGames"
);
getGroupsByTeamId = this.asyncHandler(
async (req, res) => {
const teamId = req?.user?.teamId;
if (!teamId) {
throw this.errorService.createBadRequestError("Team ID is required");
}
const groups = await this.monitorService.getGroupsByTeamId({ teamId });
return res.success({
msg: "OK",
data: groups,
});
},
SERVICE_NAME,
"getGroupsByTeamId"
);
}
export default MonitorController;
-35
View File
@@ -54,35 +54,6 @@ const networkInterfaceSchema = mongoose.Schema({
fifo_out: { type: Number, default: 0 },
});
const portSchema = mongoose.Schema({
port: { type: String },
protocol: { type: String },
});
const healthSchema = mongoose.Schema({
healthy: { type: Boolean, default: false },
source: { type: String, default: "" },
message: { type: String, default: "" },
});
const containerSchema = mongoose.Schema({
container_id: { type: String, default: "" },
container_name: { type: String, default: "" },
status: { type: String, default: "" },
health: {
type: healthSchema,
default: () => ({}),
},
running: { type: Boolean, default: false },
base_image: { type: String, default: "" },
exposed_ports: {
type: [portSchema],
default: () => [],
},
started_at: { type: Number, default: 0 },
finished_at: { type: Number, default: 0 },
});
const CheckSchema = new mongoose.Schema(
{
// Common fields
@@ -177,12 +148,6 @@ const CheckSchema = new mongoose.Schema(
default: () => [],
},
// Docker fields
docker: {
type: [containerSchema],
default: () => [],
},
// PageSpeed fields
accessibility: {
type: Number,
-9
View File
@@ -128,15 +128,6 @@ const MonitorSchema = mongoose.Schema(
gameId: {
type: String,
},
group: {
type: String,
trim: true,
maxLength: 50,
default: null,
set: function (value) {
return value && value.trim() ? value.trim() : null;
},
},
},
{
timestamps: true,
+1 -11
View File
@@ -16,7 +16,7 @@ const NotificationSchema = mongoose.Schema(
},
type: {
type: String,
enum: ["email", "slack", "discord", "webhook", "pager_duty", "matrix"],
enum: ["email", "slack", "discord", "webhook", "pager_duty"],
},
notificationName: {
type: String,
@@ -28,16 +28,6 @@ const NotificationSchema = mongoose.Schema(
phone: {
type: String,
},
// Matrix-specific fields
homeserverUrl: {
type: String,
},
roomId: {
type: String,
},
accessToken: {
type: String,
},
},
{
timestamps: true,
-15
View File
@@ -573,21 +573,6 @@ class MonitorModule {
throw error;
}
};
getGroupsByTeamId = async ({ teamId }) => {
try {
const groups = await this.Monitor.distinct("group", {
teamId: new this.ObjectId(teamId),
group: { $ne: null, $ne: "" },
});
return groups.filter(Boolean).sort();
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getGroupsByTeamId";
throw error;
}
};
}
export default MonitorModule;
+2 -2
View File
@@ -175,7 +175,7 @@
"checkmate": "Checkmate",
"url": "URL",
"unknown": "Unknown",
"uptimeAlert": "Uptime Alert: Your monitor {monitorName} is back online",
"downtimeAlert": "Downtime Alert: Your monitor {monitorName} went offline"
"uptimeAlert": "Uptime Alert: One of your monitors is back online",
"downtimeAlert": "Downtime Alert: One of your monitors went offline"
}
}
@@ -1,5 +1,5 @@
import { Router } from "express";
import MaintenanceWindow from "../../db/v1/models/MaintenanceWindow.js";
class MaintenanceWindowRoutes {
constructor(maintenanceWindowController) {
this.router = Router();
-1
View File
@@ -18,7 +18,6 @@ class MonitorRoutes {
this.router.get("/team", this.monitorController.getMonitorsByTeamId);
this.router.get("/team/with-checks", this.monitorController.getMonitorsWithChecksByTeamId);
this.router.get("/team/summary", this.monitorController.getMonitorsAndSummaryByTeamId);
this.router.get("/team/groups", this.monitorController.getGroupsByTeamId);
// Uptime routes
this.router.get("/uptime/details/:monitorId", this.monitorController.getUptimeDetailsById);
@@ -267,11 +267,6 @@ class MonitorService {
getAllGames = () => {
return this.games;
};
getGroupsByTeamId = async ({ teamId }) => {
const groups = await this.db.monitorModule.getGroupsByTeamId({ teamId });
return groups;
};
}
export default MonitorService;
+43 -16
View File
@@ -83,24 +83,45 @@ class UserService {
loginUser = async (email, password) => {
// Check if user exists
const user = await this.db.userModule.getUserByEmail(email);
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
try {
const user = await this.db.userModule.getUserByEmail(email);
// Add null check before password comparison
if (!user || !user.comparePassword) {
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
}
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return { user: userWithoutPassword, token };
} catch (error) {
// Log specific errors while returning generic message for security
this.logger.error({
message: "Login attempt failed",
service: SERVICE_NAME,
method: "loginUser",
error: error.message,
stack: error.stack,
});
// If user is not found, throw a generic authentication error for security
// Don't reveal whether user exists or password is wrong
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return { user: userWithoutPassword, token };
};
editUser = async (updates, file, currentUser) => {
@@ -111,6 +132,12 @@ class UserService {
updates.email = currentUser.email;
// Get user
const user = await this.db.userModule.getUserByEmail(currentUser.email);
// Add null check before password comparison
if (!user || !user.comparePassword) {
throw this.errorService.createAuthorizationError(this.stringService.authIncorrectPassword);
}
// Compare passwords
const match = await user.comparePassword(updates?.password);
// If not a match, throw a 403
@@ -35,12 +35,8 @@ class SuperSimpleQueue {
this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob());
const monitors = await this.db.monitorModule.getAllMonitors();
for (const monitor of monitors) {
const randomOffset = Math.floor(Math.random() * 100);
setTimeout(() => {
this.addJob(monitor._id, monitor);
}, randomOffset);
await this.addJob(monitor._id, monitor);
}
return true;
} catch (error) {
this.logger.error({
@@ -46,7 +46,7 @@ class EmailService {
*/
this.loadTemplate = (templateName) => {
try {
const templatePath = this.path.join(__dirname, `../../../templates/${templateName}.mjml`);
const templatePath = this.path.join(__dirname, `../../templates/${templateName}.mjml`);
const templateContent = this.fs.readFileSync(templatePath, "utf8");
return this.compile(templateContent);
} catch (error) {
@@ -1,4 +1,3 @@
import CacheableLookup from "cacheable-lookup";
const SERVICE_NAME = "NetworkService";
class NetworkService {
@@ -16,6 +15,7 @@ class NetworkService {
this.NETWORK_ERROR = 5000;
this.PING_ERROR = 5001;
this.axios = axios;
this.got = got;
this.https = https;
this.jmespath = jmespath;
this.GameDig = GameDig;
@@ -26,16 +26,6 @@ class NetworkService {
this.net = net;
this.stringService = stringService;
this.settingsService = settingsService;
const cacheable = new CacheableLookup();
this.got = got.extend({
dnsCache: cacheable,
timeout: {
request: 30000,
},
retry: { limit: 1 },
});
}
// Helper functions
@@ -286,7 +276,7 @@ class NetworkService {
}
}
async requestLocalDocker(monitor) {
async requestDocker(monitor) {
try {
if (!monitor.url) {
throw new Error("Monitor URL is required");
@@ -330,7 +320,7 @@ class NetworkService {
this.logger.warn({
message: `No container found for "${monitor.url}".`,
service: this.SERVICE_NAME,
method: "requestLocalDocker",
method: "requestDocker",
details: { url: monitor.url },
});
@@ -350,7 +340,7 @@ class NetworkService {
this.logger.warn({
message: `Ambiguous container match for "${monitor.url}". Matched by: ${matchTypes.join(", ")}. Using ${exactIdMatch ? "exact ID" : exactNameMatch ? "exact name" : "partial ID"} match.`,
service: this.SERVICE_NAME,
method: "requestLocalDocker",
method: "requestDocker",
details: { url: monitor.url },
});
dockerResponse.status = 404;
@@ -375,112 +365,6 @@ class NetworkService {
}
return dockerResponse;
} catch (err) {
err.service = this.SERVICE_NAME;
err.method = "requestLocalDocker";
throw err;
}
}
async requestCaptureDocker(monitor) {
try {
if (!monitor.url) {
throw new Error("Monitor URL is required");
}
const dockerResponse = {
monitorId: monitor._id,
teamId: monitor.teamId,
type: monitor.type,
};
// Build Capture API URL
const captureUrl = new URL(monitor.url);
const apiUrl = `${captureUrl.protocol}//${captureUrl.host}/api/v1/metrics/docker`;
// Make request to Capture API
const { response, responseTime, error } = await this.timeRequest(async () => {
return await this.got(apiUrl, {
headers: {
Authorization: `Bearer ${monitor.secret || ""}`,
},
timeout: { request: 10000 },
responseType: "json",
});
});
dockerResponse.responseTime = responseTime;
// Handle errors
if (error) {
const statusCode = error.response?.statusCode || this.NETWORK_ERROR;
dockerResponse.status = false;
dockerResponse.code = statusCode;
if (statusCode === 401) {
dockerResponse.message = "Invalid API secret for Capture server";
} else if (statusCode === 404) {
dockerResponse.message = "Docker monitoring not available (Capture version too old or endpoint not found)";
} else if (statusCode === 500) {
dockerResponse.message = "Docker daemon unavailable on Capture server";
} else {
dockerResponse.message = error.message || "Failed to fetch Docker metrics from Capture";
}
return dockerResponse;
}
// Parse response
const payload = response.body || response;
const { data, capture, errors } = payload;
// Check for errors array
if (errors && errors.length > 0) {
// Check if it's a critical error (docker.client)
const dockerClientError = errors.find((e) => e.metric && e.metric.includes("docker.client"));
if (dockerClientError) {
dockerResponse.status = false;
dockerResponse.code = 500;
dockerResponse.message = dockerClientError.err || "Docker daemon unavailable";
return dockerResponse;
}
}
// Check if we have container data
if (!data || !Array.isArray(data) || data.length === 0) {
dockerResponse.status = false;
dockerResponse.code = 404;
dockerResponse.message = "No containers found on Capture server";
dockerResponse.payload = { data: [], capture, errors: errors || [] };
return dockerResponse;
}
// Successful response - store all containers
dockerResponse.status = true;
dockerResponse.code = 200;
dockerResponse.message = `Found ${data.length} container(s) on Capture server`;
dockerResponse.payload = { data, capture, errors: errors || [] };
return dockerResponse;
} catch (err) {
err.service = this.SERVICE_NAME;
err.method = "requestCaptureDocker";
throw err;
}
}
async requestDocker(monitor) {
try {
if (!monitor.url) {
throw new Error("Monitor URL is required");
}
// Check if URL is HTTP/HTTPS (Capture API) or container name/ID (local)
if (monitor.url.startsWith("http://") || monitor.url.startsWith("https://")) {
return await this.requestCaptureDocker(monitor);
} else {
return await this.requestLocalDocker(monitor);
}
} catch (err) {
err.service = this.SERVICE_NAME;
err.method = "requestDocker";
@@ -645,42 +529,6 @@ class NetworkService {
throw error;
}
}
async requestMatrix({ homeserverUrl, accessToken, roomId, message }) {
try {
const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message?access_token=${accessToken}`;
const body = {
msgtype: "m.text",
body: message,
format: "org.matrix.custom.html",
formatted_body: message,
};
const response = await this.axios.post(url, body, {
headers: {
"Content-Type": "application/json",
},
});
return {
status: true,
code: response.status,
message: "Successfully sent Matrix notification",
};
} catch (error) {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "requestMatrix",
});
return {
status: false,
code: error.response?.status || this.NETWORK_ERROR,
message: "Failed to send Matrix notification",
payload: error.response?.data,
};
}
}
}
export default NetworkService;
@@ -1,34 +0,0 @@
const SERVICE_NAME = "Matrix";
class Matrix {
static SERVICE_NAME = SERVICE_NAME;
constructor({ networkService, logger }) {
this.networkService = networkService;
this.logger = logger;
}
get serviceName() {
return Matrix.SERVICE_NAME;
}
async send({ friendlyName, homeserverUrl, accessToken, roomId, message, monitorName }) {
const title = `Checkmate status for ${monitorName}`;
const formattedMessage = `## ${title}\n${message}`;
try {
await this.networkService.requestMatrix({
homeserverUrl,
accessToken,
roomId,
message: formattedMessage,
});
this.logger.info(`Successfully sent Matrix notification for ${friendlyName}`);
return true;
} catch (error) {
this.logger.error(`Failed to send Matrix notification for ${friendlyName}: ${error.message}`);
return false;
}
}
}
export default Matrix;
@@ -1,5 +1,4 @@
const SERVICE_NAME = "NotificationService";
import Matrix from "./notificationProviders/matrix.js";
class NotificationService {
static SERVICE_NAME = SERVICE_NAME;
@@ -47,14 +46,6 @@ class NotificationService {
return response;
}
if (type === "matrix") {
const { friendlyName, homeserverUrl, accessToken, roomId } = notification;
const monitorName = subject;
const message = content;
const matrix = new Matrix({ networkService: this.networkService, logger: this.logger });
const success = await matrix.send({ friendlyName, homeserverUrl, accessToken, roomId, message, monitorName });
return success;
}
};
async handleNotifications(networkResponse) {
@@ -74,9 +74,7 @@ class NotificationUtils {
let discordMessageText = {
embeds: [
{
title: status
? dn.uptimeAlert.replace("{monitorName}", monitor?.name ?? dn.unknown)
: dn.downtimeAlert.replace("{monitorName}", monitor?.name ?? dn.unknown),
title: status ? dn.uptimeAlert : dn.downtimeAlert,
color: status ? 5763719 : 15548997,
fields: [
@@ -275,13 +275,6 @@ class StatusService {
check.capture = payload?.capture ?? {};
check.net = net ?? {};
}
if (type === "docker") {
const { data, capture, errors } = payload ?? {};
check.docker = data ?? [];
check.errors = errors ?? [];
check.capture = capture ?? {};
}
return check;
};
@@ -381,7 +381,7 @@ class MonitorService implements IMonitorService {
// Get monitor stats
const monitorStats = await MonitorStats.findOne({
monitorId: monitor._id,
});
}).lean();
if (!monitorStats) {
throw new ApiError("Monitor stats not found", 404);
+4 -13
View File
@@ -1,21 +1,12 @@
import sharp from "sharp";
/**
* Generates a 64 * 64 pixel image from a given image
* Converts image to base64 string without resizing
* CSS handles the 64x64 display sizing client-side
* @param {} file
*/
const GenerateAvatarImage = async (file) => {
try {
// Resize to target 64 * 64
let resizedImageBuffer = await sharp(file.buffer)
.resize({
width: 64,
height: 64,
fit: "cover",
})
.toBuffer();
//Get b64 string
const base64Image = resizedImageBuffer.toString("base64");
// Simply convert to base64 - let CSS handle the 64x64 display
const base64Image = file.buffer.toString("base64");
return base64Image;
} catch (error) {
throw error;
+2 -36
View File
@@ -174,7 +174,6 @@ const createMonitorBodyValidation = joi.object({
expectedValue: joi.string().allow(""),
matchMethod: joi.string(),
gameId: joi.string().allow(""),
group: joi.string().max(50).trim().allow(null, "").optional(),
});
const createMonitorsBodyValidation = joi.array().items(
@@ -204,7 +203,6 @@ const editMonitorBodyValidation = joi.object({
usage_temperature: joi.number(),
}),
gameId: joi.string(),
group: joi.string().max(50).trim().allow(null, "").optional(),
});
const pauseMonitorParamValidation = joi.object({
@@ -575,10 +573,10 @@ const createNotificationBodyValidation = joi.object({
"any.required": "Notification name is required",
}),
type: joi.string().valid("email", "webhook", "slack", "discord", "pager_duty", "matrix").required().messages({
type: joi.string().valid("email", "webhook", "slack", "discord", "pager_duty").required().messages({
"string.empty": "Notification type is required",
"any.required": "Notification type is required",
"any.only": "Notification type must be email, webhook, slack, discord, pager_duty, or matrix",
"any.only": "Notification type must be email, webhook, or pager_duty",
}),
address: joi.when("type", {
@@ -606,40 +604,8 @@ const createNotificationBodyValidation = joi.object({
"string.uri": "Please enter a valid Webhook URL",
}),
},
{
is: "matrix",
then: joi.string().allow("").optional(),
},
],
}),
homeserverUrl: joi.when("type", {
is: "matrix",
then: joi.string().uri().required().messages({
"string.empty": "Homeserver URL cannot be empty",
"any.required": "Homeserver URL is required",
"string.uri": "Please enter a valid Homeserver URL",
}),
otherwise: joi.string().allow("").optional(),
}),
roomId: joi.when("type", {
is: "matrix",
then: joi.string().required().messages({
"string.empty": "Room ID cannot be empty",
"any.required": "Room ID is required",
}),
otherwise: joi.string().allow("").optional(),
}),
accessToken: joi.when("type", {
is: "matrix",
then: joi.string().required().messages({
"string.empty": "Access Token cannot be empty",
"any.required": "Access Token is required",
}),
otherwise: joi.string().allow("").optional(),
}),
});
//****************************************