easy-devops 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +2 -2
  2. package/package.json +6 -3
  3. package/src/cli/index.js +13 -1
  4. package/src/cli/menus/dashboard.js +1 -1
  5. package/src/core/channels/discord.js +77 -0
  6. package/src/core/channels/telegram.js +120 -0
  7. package/src/core/db.js +8 -1
  8. package/src/core/domainNotifier.js +298 -0
  9. package/src/core/events.js +130 -0
  10. package/src/core/notifier.js +73 -0
  11. package/src/core/shell.js +59 -7
  12. package/src/dashboard/controllers/authController.js +29 -0
  13. package/src/dashboard/controllers/domainsController.js +416 -0
  14. package/src/dashboard/controllers/nginxController.js +128 -0
  15. package/src/dashboard/controllers/settingsController.js +335 -0
  16. package/src/dashboard/controllers/sslController.js +291 -0
  17. package/src/dashboard/public/img/icon.png +0 -0
  18. package/src/dashboard/public/img/icon_b.png +0 -0
  19. package/src/dashboard/public/js/app.js +234 -2
  20. package/src/dashboard/routes/auth.js +12 -22
  21. package/src/dashboard/routes/domains.js +11 -363
  22. package/src/dashboard/routes/nginx.js +13 -146
  23. package/src/dashboard/routes/settings.js +16 -189
  24. package/src/dashboard/routes/ssl.js +9 -276
  25. package/src/dashboard/server.js +24 -27
  26. package/src/dashboard/socketManager.js +282 -0
  27. package/src/dashboard/views/index.ejs +52 -0
  28. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  29. package/src/dashboard/views/partials/domains-panel.ejs +4 -0
  30. package/src/dashboard/views/partials/login.ejs +1 -1
  31. package/src/dashboard/views/partials/logs-panel.ejs +67 -0
  32. package/src/dashboard/views/partials/settings-panel.ejs +263 -87
  33. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  34. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="src/dashboard/public/img/icon.png" alt="Easy DevOps" width="100" />
2
+ <img src="src/dashboard/public/img/icon_b.png" alt="Easy DevOps" width="100" />
3
3
  </p>
4
4
 
5
5
  # Easy DevOps
@@ -110,7 +110,7 @@ npx easy-devops
110
110
  ### CLI Overview
111
111
 
112
112
  ```
113
- ███████╗███████╗ Easy DevOps v1.0.2
113
+ ███████╗███████╗ Easy DevOps v1.2.1
114
114
  ██╔════╝╚════██╗ ─────────────────────
115
115
  █████╗ ██╔╝ CLI & Web Dashboard
116
116
  ██╔══╝ ██╔╝ Nginx · SSL · Domains · Node.js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-devops",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "A unified DevOps management tool with CLI and web dashboard for managing Nginx, SSL certificates, and Node.js on Linux and Windows servers.",
5
5
  "keywords": [
6
6
  "devops",
@@ -55,12 +55,15 @@
55
55
  "acme-client": "^5.4.0",
56
56
  "chalk": "^5.3.0",
57
57
  "cli-table3": "^0.6.5",
58
+ "discord.js": "^14.26.2",
58
59
  "ejs": "^5.0.1",
59
60
  "express": "^5.2.1",
61
+ "express-rate-limit": "^8.3.2",
60
62
  "express-session": "^1.17.3",
61
- "good.db": "^2.4.6",
63
+ "good.db": "^2.5.0",
62
64
  "inquirer": "^9.2.12",
63
65
  "ora": "^7.0.1",
66
+ "session-file-store": "^1.5.0",
64
67
  "socket.io": "^4.8.3"
65
68
  }
66
- }
69
+ }
package/src/cli/index.js CHANGED
@@ -24,6 +24,18 @@ if (process.argv[2] === 'system-info') {
24
24
  process.exit(0);
25
25
  }
26
26
 
27
+ // ─── Detection cache — only re-run if stale (>60s) ───────────────────────────
28
+ const DETECTION_TTL_MS = 60_000;
29
+ let lastDetectionAt = 0;
30
+
31
+ async function runDetectionIfStale() {
32
+ const now = Date.now();
33
+ if (now - lastDetectionAt >= DETECTION_TTL_MS) {
34
+ await runDetection();
35
+ lastDetectionAt = now;
36
+ }
37
+ }
38
+
27
39
  function renderBanner() {
28
40
  const c = chalk.hex('#d64a29');
29
41
  const dim = chalk.hex('#d64a29').dim;
@@ -90,7 +102,7 @@ async function dispatch(choice) {
90
102
  async function main() {
91
103
  while (true) {
92
104
  const spinner = ora('Checking system…').start();
93
- await runDetection();
105
+ await runDetectionIfStale();
94
106
  spinner.stop();
95
107
 
96
108
  try {
@@ -76,7 +76,7 @@ export async function getDashboardStatus() {
76
76
  const pidAlive = isPidAlive(storedPid);
77
77
  const responding = pidAlive && await httpPing(storedPort, 1000);
78
78
 
79
- if (storedPid && !pidAlive) {
79
+ if (storedPid && !responding) {
80
80
  dbSet('dashboard-pid', null);
81
81
  dbSet('dashboard-port', null);
82
82
  }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Discord Notification Channel
3
+ *
4
+ * Sends notifications to Discord via webhook using discord.js.
5
+ * This module conforms to the channel interface defined in notifier.js:
6
+ * - Exports async function send(event, channelConfig)
7
+ * - channelConfig must contain { webhookUrl }
8
+ *
9
+ * NO IMPORTS from other project files.
10
+ */
11
+
12
+ import { WebhookClient, EmbedBuilder } from 'discord.js';
13
+
14
+ const SEVERITY_COLORS = {
15
+ danger: 0xE74C3C, // red
16
+ warning: 0xFFFF00, // yellow
17
+ };
18
+ const DEFAULT_COLOR = 0x3498DB; // blue
19
+
20
+ /**
21
+ * Convert event type to a human-readable title.
22
+ * e.g., 'domain_added' -> 'Domain Added'
23
+ * @param {string} type - Event type
24
+ * @returns {string} Formatted title
25
+ */
26
+ function toTitle(type) {
27
+ if (!type) return 'Notification';
28
+ return type.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
29
+ }
30
+
31
+ /**
32
+ * Send a notification to Discord via webhook.
33
+ *
34
+ * @param {Object} event - The notification event
35
+ * @param {string} event.type - Event type for embed title
36
+ * @param {string} [event.message] - Message to include in description
37
+ * @param {string} [event.severity] - 'danger' (red) or 'warning' (yellow)
38
+ * @param {string} [event.domain] - Domain to include in description
39
+ * @param {string} [event.timestamp] - ISO timestamp (defaults to now)
40
+ * @param {Object} channelConfig - Channel configuration
41
+ * @param {string} channelConfig.webhookUrl - Discord webhook URL
42
+ * @param {string} [channelConfig.message] - Optional prefix to prepend to message
43
+ * @returns {Promise<void>}
44
+ */
45
+ export async function send(event, channelConfig) {
46
+ // Early return if not configured - no throw, just exit silently
47
+ if (!channelConfig?.webhookUrl) return;
48
+
49
+ // Determine embed colour based on severity
50
+ const color = SEVERITY_COLORS[event?.severity] ?? DEFAULT_COLOR;
51
+
52
+ // Build description from available fields
53
+ const lines = [];
54
+ if (event?.message) lines.push(event.message);
55
+ if (event?.domain) lines.push(`Domain: \`${event.domain}\``);
56
+ const description = lines.join('\n') || 'No additional details.';
57
+
58
+ // Build Discord embed using EmbedBuilder
59
+ const embed = new EmbedBuilder()
60
+ .setAuthor({ name: 'Easy DevOps', iconURL: 'https://raw.githubusercontent.com/omar00050/Easy-DevOps/main/src/dashboard/public/img/icon_b.png' })
61
+ .setTitle(toTitle(event?.type))
62
+ .setDescription(description)
63
+ .setColor(color)
64
+ .setFooter({ text: 'Easy DevOps' })
65
+ .setTimestamp(event?.timestamp ? new Date(event.timestamp) : new Date());
66
+
67
+ // Send via WebhookClient
68
+ // The message prefix (e.g. role mention) goes in `content`, not the embed,
69
+ // because Discord only resolves mentions in message content, not inside embeds.
70
+ const webhook = new WebhookClient({ url: channelConfig.webhookUrl });
71
+ await webhook.send({
72
+ content: channelConfig.message || undefined,
73
+ embeds: [embed],
74
+ username: 'Easy DevOps logs',
75
+ avatarURL: 'https://raw.githubusercontent.com/omar00050/Easy-DevOps/main/src/dashboard/public/img/icon_b.png',
76
+ });
77
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Telegram Notification Channel
3
+ *
4
+ * Sends notifications to Telegram via Bot API.
5
+ * This module conforms to the channel interface defined in notifier.js:
6
+ * - Exports async function send(event, channelConfig)
7
+ * - channelConfig must contain { botToken, chatId }
8
+ *
9
+ * NO IMPORTS: fetch is global in Node 18+. This module does not import
10
+ * from notifier.js or any other project files.
11
+ */
12
+
13
+ /**
14
+ * Escape HTML special characters for Telegram HTML parse mode.
15
+ * @param {string} str - String to escape
16
+ * @returns {string} HTML-safe string
17
+ */
18
+ function escapeHtml(str) {
19
+ if (!str) return '';
20
+ return str
21
+ .replace(/&/g, '&amp;')
22
+ .replace(/</g, '&lt;')
23
+ .replace(/>/g, '&gt;');
24
+ }
25
+
26
+ /**
27
+ * Convert event type to a human-readable title.
28
+ * e.g., 'domain_added' -> 'Domain Added'
29
+ * @param {string} type - Event type
30
+ * @returns {string} Formatted title
31
+ */
32
+ function toTitle(type) {
33
+ if (!type) return 'Notification';
34
+ return type.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
35
+ }
36
+
37
+ /**
38
+ * Get severity emoji prefix for Telegram messages.
39
+ * @param {string} severity - 'danger', 'warning', or undefined/other
40
+ * @returns {string} Emoji prefix or empty string
41
+ */
42
+ function severityPrefix(severity) {
43
+ if (severity === 'danger') return '\uD83D\uDD34 DANGER';
44
+ if (severity === 'warning') return '\u26A0\uFE0F WARNING';
45
+ return '';
46
+ }
47
+
48
+ /**
49
+ * Send a notification to Telegram via Bot API.
50
+ *
51
+ * @param {Object} event - The notification event
52
+ * @param {string} event.type - Event type for message title
53
+ * @param {string} [event.message] - Message to include
54
+ * @param {string} [event.severity] - 'danger' or 'warning'
55
+ * @param {string} [event.domain] - Domain to include
56
+ * @param {string} [event.timestamp] - ISO timestamp (defaults to now)
57
+ * @param {Object} channelConfig - Channel configuration
58
+ * @param {string} channelConfig.botToken - Telegram bot token
59
+ * @param {string} channelConfig.chatId - Telegram chat ID
60
+ * @param {string} [channelConfig.message] - Optional prefix to prepend to message
61
+ * @returns {Promise<void>}
62
+ */
63
+ export async function send(event, channelConfig) {
64
+ // Early return if not configured - no throw, just exit silently
65
+ if (!channelConfig?.botToken || !channelConfig?.chatId) return;
66
+ try {
67
+ // Prepend message prefix if configured
68
+ if (channelConfig?.message) {
69
+ event = {
70
+ ...event,
71
+ message: channelConfig.message + '\n' + (event.message || '')
72
+ };
73
+ }
74
+
75
+ // Build message text using HTML formatting
76
+ const lines = [];
77
+
78
+ // Add severity prefix if present
79
+ const prefix = severityPrefix(event?.severity);
80
+ if (prefix) lines.push(`<b>${prefix}</b>`);
81
+
82
+ // Add event type as title
83
+ lines.push(`<b>${escapeHtml(toTitle(event?.type))}</b>`);
84
+
85
+ // Add message body if present (HTML escaped)
86
+ if (event?.message) {
87
+ lines.push(escapeHtml(event.message));
88
+ }
89
+
90
+ // Add domain if present (as inline code)
91
+ if (event?.domain) {
92
+ lines.push(`Domain: <code>${escapeHtml(event.domain)}</code>`);
93
+ }
94
+
95
+ const text = lines.join('\n');
96
+
97
+ // Build Telegram Bot API URL
98
+ const url = `https://api.telegram.org/bot${channelConfig.botToken}/sendMessage`;
99
+
100
+ // POST to Telegram API using built-in fetch (Node 18+)
101
+ const res = await fetch(url, {
102
+ method: 'POST',
103
+ headers: { 'Content-Type': 'application/json' },
104
+ body: JSON.stringify({
105
+ chat_id: channelConfig.chatId,
106
+ text,
107
+ parse_mode: 'HTML',
108
+ }),
109
+ });
110
+ // Throw on non-2xx response
111
+ if (!res.ok) {
112
+ throw new Error(`Telegram API returned ${res.status} ${res.statusText}`);
113
+ }
114
+ } catch (err) {
115
+ // Redact bot token from error message to prevent credential leakage
116
+ const safeMsg = err.message.replace(/bot[^/]+\//g, 'bot[REDACTED]/');
117
+ console.error('[telegram] send failed:', safeMsg);
118
+ // DO NOT re-throw - channel isolation guarantees other channels still work
119
+ }
120
+ }
package/src/core/db.js CHANGED
@@ -41,7 +41,14 @@ try {
41
41
  let db;
42
42
 
43
43
  function createDbConnection() {
44
- return new GoodDB(new SQLiteDriver({ path: DB_PATH }));
44
+ return new GoodDB(new SQLiteDriver({ path: DB_PATH }), {
45
+ nested: "..",
46
+ nestedIsEnabled: true,
47
+ cache: {
48
+ capacity: 1024,
49
+ isEnabled: true,
50
+ }
51
+ });
45
52
  }
46
53
 
47
54
  try {
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Per-domain notification config storage.
3
+ * SQLite key: 'domain_notification_config'
4
+ *
5
+ * Config shape per domain:
6
+ * { nginx_down: { enabled: bool, channelIds: [uuid, ...] }, ... }
7
+ *
8
+ * channelIds are UUIDs referencing entries in the notification_channels key.
9
+ * Empty channelIds means dashboard-only (no external dispatch).
10
+ *
11
+ * Also tracks notification state to prevent spam and support recovery notifications.
12
+ * SQLite key: 'notification_state'
13
+ */
14
+
15
+ import { dbGet, dbSet } from './db.js';
16
+
17
+ const DB_KEY = 'domain_notification_config';
18
+ const STATE_DB_KEY = 'notification_state';
19
+ const KNOWN_EVENT_TYPES = ['nginx_down', 'cert_expiry', 'domain_health'];
20
+
21
+ /**
22
+ * Default notification config returned for unconfigured domains.
23
+ * All events enabled, no external channels (dashboard-only) — opt-in model.
24
+ */
25
+ export const DOMAIN_NOTIF_DEFAULTS = {
26
+ nginx_down: { enabled: true, channelIds: [] },
27
+ cert_expiry: { enabled: true, channelIds: [] },
28
+ domain_health: { enabled: true, channelIds: [] },
29
+ };
30
+
31
+ /**
32
+ * Validates a domain notification config object.
33
+ * @param {object} config
34
+ * @throws {Error} with descriptive message on invalid input
35
+ */
36
+ function validateDomainNotifConfig(config) {
37
+ if (typeof config !== 'object' || config === null) {
38
+ throw new Error('Config must be a non-null object');
39
+ }
40
+
41
+ for (const key of Object.keys(config)) {
42
+ if (!KNOWN_EVENT_TYPES.includes(key)) {
43
+ throw new Error(`Invalid event type: '${key}'. Known types: ${KNOWN_EVENT_TYPES.join(', ')}`);
44
+ }
45
+
46
+ const entry = config[key];
47
+ if (typeof entry !== 'object' || entry === null) {
48
+ throw new Error(`Entry for '${key}' must be an object`);
49
+ }
50
+
51
+ if (typeof entry.enabled !== 'boolean') {
52
+ throw new Error(`Entry for '${key}' must have boolean 'enabled' field`);
53
+ }
54
+
55
+ if (!Array.isArray(entry.channelIds)) {
56
+ throw new Error(`Entry for '${key}' must have array 'channelIds' field`);
57
+ }
58
+
59
+ for (const id of entry.channelIds) {
60
+ if (typeof id !== 'string') {
61
+ throw new Error(`channelIds in '${key}' must contain only strings`);
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Returns the stored notification config for a domain, falling back to defaults.
69
+ * @param {string} domain
70
+ * @returns {object}
71
+ */
72
+ export function getDomainNotifConfig(domain) {
73
+ let map;
74
+ try {
75
+ map = dbGet(DB_KEY);
76
+ } catch {
77
+ return { ...DOMAIN_NOTIF_DEFAULTS };
78
+ }
79
+
80
+ if (!map || typeof map !== 'object') {
81
+ return { ...DOMAIN_NOTIF_DEFAULTS };
82
+ }
83
+
84
+ return map[domain] ? { ...map[domain] } : { ...DOMAIN_NOTIF_DEFAULTS };
85
+ }
86
+
87
+ /**
88
+ * Saves notification config for a domain.
89
+ * @param {string} domain
90
+ * @param {object} config
91
+ * @throws {Error} if config is invalid
92
+ */
93
+ export function saveDomainNotifConfig(domain, config) {
94
+ validateDomainNotifConfig(config);
95
+
96
+ let map = dbGet(DB_KEY);
97
+ if (!map || typeof map !== 'object') {
98
+ map = {};
99
+ }
100
+
101
+ map[domain] = config;
102
+ dbSet(DB_KEY, map);
103
+ }
104
+
105
+ /**
106
+ * Returns the channel IDs that should receive a given event for a domain.
107
+ * Returns [] when the event is disabled or has no channels assigned.
108
+ * @param {string|null} domain
109
+ * @param {string} eventType
110
+ * @returns {string[]}
111
+ */
112
+ export function getEffectiveChannelIds(domain, eventType) {
113
+ if (!KNOWN_EVENT_TYPES.includes(eventType)) {
114
+ return [];
115
+ }
116
+
117
+ const config = getDomainNotifConfig(domain);
118
+ const entry = config[eventType];
119
+
120
+ if (!entry || !entry.enabled) {
121
+ return [];
122
+ }
123
+
124
+ return Array.isArray(entry.channelIds) ? [...entry.channelIds] : [];
125
+ }
126
+
127
+ /**
128
+ * Returns the union of channel IDs configured for a given event type across all domains.
129
+ * Useful for global events (nginx_down) where no specific domain context exists.
130
+ * @param {string} eventType
131
+ * @returns {string[]}
132
+ */
133
+ export function getAllDomainChannelIds(eventType) {
134
+ if (!KNOWN_EVENT_TYPES.includes(eventType)) return [];
135
+
136
+ let map;
137
+ try {
138
+ map = dbGet(DB_KEY);
139
+ } catch {
140
+ return [];
141
+ }
142
+
143
+ if (!map || typeof map !== 'object') return [];
144
+
145
+ const ids = new Set();
146
+ for (const domainConfig of Object.values(map)) {
147
+ if (!domainConfig || typeof domainConfig !== 'object') continue;
148
+ const entry = domainConfig[eventType];
149
+ if (entry?.enabled && Array.isArray(entry.channelIds)) {
150
+ for (const id of entry.channelIds) ids.add(id);
151
+ }
152
+ }
153
+
154
+ return [...ids];
155
+ }
156
+
157
+ // ═══════════════════════════════════════════════════════════════════════════
158
+ // NOTIFICATION STATE TRACKING (deduplication + recovery)
159
+ // ═══════════════════════════════════════════════════════════════════════════
160
+
161
+ /**
162
+ * State key format: "{domain}:{eventType}" or "global:{eventType}" (for nginx_down)
163
+ * State value: { status: 'up'|'down'|'unknown', lastNotifiedAt: timestamp, notifiedFor: 'up'|'down'|null }
164
+ */
165
+
166
+ /**
167
+ * Get the notification state map from database.
168
+ * @returns {object}
169
+ */
170
+ function getNotificationStateMap() {
171
+ try {
172
+ const map = dbGet(STATE_DB_KEY);
173
+ return map && typeof map === 'object' ? map : {};
174
+ } catch {
175
+ return {};
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Save the notification state map to database.
181
+ * @param {object} map
182
+ */
183
+ function saveNotificationStateMap(map) {
184
+ dbSet(STATE_DB_KEY, map);
185
+ }
186
+
187
+ /**
188
+ * Get notification state for a specific domain/event combination.
189
+ * @param {string|null} domain - null for global events like nginx_down
190
+ * @param {string} eventType
191
+ * @returns {{ status: string, lastNotifiedAt: number|null, notifiedFor: string|null }}
192
+ */
193
+ export function getNotificationState(domain, eventType) {
194
+ const key = domain ? `${domain}:${eventType}` : `global:${eventType}`;
195
+ const map = getNotificationStateMap();
196
+ return map[key] || { status: 'unknown', lastNotifiedAt: null, notifiedFor: null };
197
+ }
198
+
199
+ /**
200
+ * Set notification state for a specific domain/event combination.
201
+ * @param {string|null} domain - null for global events
202
+ * @param {string} eventType
203
+ * @param {object} state - { status, lastNotifiedAt, notifiedFor }
204
+ */
205
+ export function setNotificationState(domain, eventType, state) {
206
+ const key = domain ? `${domain}:${eventType}` : `global:${eventType}`;
207
+ const map = getNotificationStateMap();
208
+ map[key] = {
209
+ status: state.status || 'unknown',
210
+ lastNotifiedAt: state.lastNotifiedAt || null,
211
+ notifiedFor: state.notifiedFor || null,
212
+ };
213
+ saveNotificationStateMap(map);
214
+ }
215
+
216
+ /**
217
+ * Result of checking if a notification should be sent.
218
+ * @typedef {Object} NotificationDecision
219
+ * @property {boolean} shouldNotify - Whether to send a notification
220
+ * @property {string|null} reason - Why (e.g., 'state_changed', 'recovery', 'no_change')
221
+ * @property {string} currentStatus - The new status ('up' or 'down')
222
+ * @property {string|null} previousNotifiedFor - What we previously notified about
223
+ */
224
+
225
+ /**
226
+ * Determine if we should send a notification based on state changes.
227
+ * Prevents spam by only sending when state changes.
228
+ * Handles recovery notifications when transitioning from down → up.
229
+ *
230
+ * @param {string|null} domain - null for global events
231
+ * @param {string} eventType
232
+ * @param {string} currentStatus - 'up' or 'down'
233
+ * @returns {NotificationDecision}
234
+ */
235
+ export function shouldSendNotification(domain, eventType, currentStatus) {
236
+ const previousState = getNotificationState(domain, eventType);
237
+ const previousNotifiedFor = previousState.notifiedFor;
238
+
239
+ // Normalize status to 'up' or 'down'
240
+ const status = currentStatus === 'up' || currentStatus === 'down' ? currentStatus : 'unknown';
241
+
242
+ console.log(`[domainNotifier] Checking notification: domain=${domain || 'global'}, event=${eventType}, status=${status}, prevNotifiedFor=${previousNotifiedFor}`);
243
+
244
+ // First time seeing this domain/event - don't notify, just record state
245
+ if (previousNotifiedFor === null || previousState.status === 'unknown') {
246
+ console.log(`[domainNotifier] First check - recording state, no notification`);
247
+ setNotificationState(domain, eventType, { status, lastNotifiedAt: null, notifiedFor: status });
248
+ return { shouldNotify: false, reason: 'first_check', currentStatus: status, previousNotifiedFor: null };
249
+ }
250
+
251
+ // Status unchanged from what we already notified about
252
+ if (previousNotifiedFor === status) {
253
+ console.log(`[domainNotifier] No change - already notified for '${status}'`);
254
+ return { shouldNotify: false, reason: 'no_change', currentStatus: status, previousNotifiedFor };
255
+ }
256
+
257
+ // Status changed!
258
+ if (status === 'down' && previousNotifiedFor !== 'down') {
259
+ // Transition: up → down (or unknown → down)
260
+ console.log(`[domainNotifier] State changed: ${previousNotifiedFor} → down, will notify`);
261
+ setNotificationState(domain, eventType, { status: 'down', lastNotifiedAt: Date.now(), notifiedFor: 'down' });
262
+ return { shouldNotify: true, reason: 'state_changed', currentStatus: 'down', previousNotifiedFor };
263
+ }
264
+
265
+ if (status === 'up' && previousNotifiedFor === 'down') {
266
+ // Transition: down → up (recovery!)
267
+ console.log(`[domainNotifier] Recovery detected: down → up, will notify`);
268
+ setNotificationState(domain, eventType, { status: 'up', lastNotifiedAt: Date.now(), notifiedFor: 'up' });
269
+ return { shouldNotify: true, reason: 'recovery', currentStatus: 'up', previousNotifiedFor: 'down' };
270
+ }
271
+
272
+ // Edge case: up → up (but previousNotifiedFor was something else)
273
+ // This shouldn't happen, but handle gracefully
274
+ console.log(`[domainNotifier] Edge case: status=${status}, prevNotifiedFor=${previousNotifiedFor}`);
275
+ setNotificationState(domain, eventType, { status, lastNotifiedAt: Date.now(), notifiedFor: status });
276
+ return { shouldNotify: false, reason: 'edge_case', currentStatus: status, previousNotifiedFor };
277
+ }
278
+
279
+ /**
280
+ * Clear notification state for a domain (useful for testing or manual reset).
281
+ * @param {string|null} domain - null to clear global state, or specific domain
282
+ * @param {string} eventType
283
+ */
284
+ export function clearNotificationState(domain, eventType) {
285
+ const key = domain ? `${domain}:${eventType}` : `global:${eventType}`;
286
+ const map = getNotificationStateMap();
287
+ delete map[key];
288
+ saveNotificationStateMap(map);
289
+ }
290
+
291
+ /**
292
+ * Clear all notification state (useful for testing).
293
+ */
294
+ export function clearAllNotificationState() {
295
+ dbSet(STATE_DB_KEY, {});
296
+ }
297
+
298
+ export { KNOWN_EVENT_TYPES };