easy-devops 1.2.0 → 1.3.0
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.
- package/README.md +97 -6
- package/dist/ui/assets/index-B6zdwEnG.css +1 -0
- package/dist/ui/assets/index-Cy0oNmul.js +442 -0
- package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
- package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
- package/dist/ui/brand/apple-touch-icon.png +0 -0
- package/dist/ui/brand/favicon-16.png +0 -0
- package/dist/ui/brand/favicon-32.png +0 -0
- package/dist/ui/brand/favicon-light-16.png +0 -0
- package/dist/ui/brand/favicon-light-32.png +0 -0
- package/dist/ui/brand/favicon.ico +0 -0
- package/dist/ui/brand/icon-192.png +0 -0
- package/dist/ui/brand/icon-48.png +0 -0
- package/dist/ui/brand/icon-512.png +0 -0
- package/dist/ui/brand/icon-64-light.png +0 -0
- package/dist/ui/brand/icon-64.png +0 -0
- package/dist/ui/brand/logo-dark.png +0 -0
- package/dist/ui/brand/logo-light.png +0 -0
- package/dist/ui/brand/mark-dark.png +0 -0
- package/dist/ui/brand/mark-light.png +0 -0
- package/dist/ui/index.html +71 -0
- package/install.ps1 +188 -1
- package/install.sh +254 -29
- package/package.json +17 -5
- package/src/cli/dash.js +110 -0
- package/src/cli/index.js +237 -106
- package/src/cli/managers/domain-manager.js +60 -40
- package/src/cli/managers/ssl-manager.js +47 -330
- package/src/cli/menu.js +156 -0
- package/src/cli/menus/cleanup.js +205 -0
- package/src/cli/menus/dashboard.js +93 -2
- package/src/cli/menus/runtime.js +236 -0
- package/src/cli/menus/service.js +764 -0
- package/src/cli/menus/settings.js +176 -8
- package/src/cli/menus/uninstall.js +167 -0
- package/src/cli/menus/update.js +221 -65
- package/src/core/acme-challenge.js +273 -0
- package/src/core/cert-operations.js +189 -0
- package/src/{dashboard/lib → core}/cert-reader.js +2 -2
- package/src/core/cert-renewal.js +494 -0
- package/src/core/channels/discord.js +77 -0
- package/src/core/channels/telegram.js +120 -0
- package/src/core/cleanup.js +600 -0
- package/src/core/config.js +169 -2
- package/src/core/daemon/ipc.js +292 -0
- package/src/core/daemon/lock.js +294 -0
- package/src/core/daemon/run.js +241 -0
- package/src/core/daemon/stopRequest.js +162 -0
- package/src/core/db.js +44 -8
- package/src/core/deploy/apps.js +491 -0
- package/src/core/deploy/domainLink.js +200 -0
- package/src/core/deploy/engine.js +973 -0
- package/src/core/deploy/ezfile.js +361 -0
- package/src/core/deploy/github.js +239 -0
- package/src/core/deploy/githubApi.js +261 -0
- package/src/core/deploy/hookServer.js +325 -0
- package/src/core/deploy/hubCommands.js +267 -0
- package/src/core/deploy/launcher.js +57 -0
- package/src/core/deploy/status.js +91 -0
- package/src/core/deploy/store.js +398 -0
- package/src/core/domainNotifier.js +364 -0
- package/src/core/domains-db.js +234 -0
- package/src/core/events.js +222 -0
- package/src/core/hub/agent.js +842 -0
- package/src/core/hubLink.js +306 -0
- package/src/core/hubPermissions.js +430 -0
- package/src/core/installSource.js +162 -0
- package/src/core/jobs/bus.js +120 -0
- package/src/core/jobs/index.js +371 -0
- package/src/core/jobs/monitors.js +368 -0
- package/src/core/jobs/owner.js +217 -0
- package/src/core/jobs/revisionWatcher.js +106 -0
- package/src/core/nginx-apply.js +213 -0
- package/src/core/nginx-conf-generator.js +253 -17
- package/src/{dashboard/lib → core}/nginx-service.js +18 -9
- package/src/core/notifications/claim.js +214 -0
- package/src/core/notifications/dispatch.js +154 -0
- package/src/core/notifier.js +103 -0
- package/src/core/passwords.js +172 -0
- package/src/core/permissions.js +8 -4
- package/src/core/platform.js +709 -2
- package/src/core/probeCache.js +258 -0
- package/src/core/purge.js +372 -0
- package/src/core/runner.js +488 -0
- package/src/core/service/acl.js +226 -0
- package/src/core/service/dataDir.js +345 -0
- package/src/core/service/index.js +1128 -0
- package/src/core/service/legacy.js +218 -0
- package/src/core/service/runtime.js +446 -0
- package/src/core/service/runtimeUpdate.js +800 -0
- package/src/core/service/systemd.js +458 -0
- package/src/core/service/windowsPersonal.js +530 -0
- package/src/core/service/windowsService.js +576 -0
- package/src/core/service/winsw.js +260 -0
- package/src/core/setupCode.js +331 -0
- package/src/core/shell.js +128 -13
- package/src/core/ssl-issuer.js +627 -0
- package/src/core/updater.js +295 -0
- package/src/core/validators.js +99 -0
- package/src/dashboard/controllers/authController.js +316 -0
- package/src/dashboard/controllers/deploymentsController.js +479 -0
- package/src/dashboard/controllers/domainsController.js +403 -0
- package/src/dashboard/controllers/hubController.js +135 -0
- package/src/dashboard/controllers/nginxController.js +146 -0
- package/src/dashboard/controllers/processesController.js +368 -0
- package/src/dashboard/controllers/settingsController.js +503 -0
- package/src/dashboard/controllers/sslController.js +452 -0
- package/src/dashboard/lib/daemonBridge.js +163 -0
- package/src/dashboard/lib/localRequest.js +235 -0
- package/src/dashboard/lib/loginRateLimit.js +119 -0
- package/src/dashboard/lib/requireAuth.js +80 -0
- package/src/dashboard/public/img/icon.png +0 -0
- package/src/dashboard/public/img/icon_b.png +0 -0
- package/src/dashboard/public/js/app.js +595 -19
- package/src/dashboard/routes/auth.js +14 -33
- package/src/dashboard/routes/deployments.js +46 -0
- package/src/dashboard/routes/domains.js +20 -363
- package/src/dashboard/routes/hub.js +22 -0
- package/src/dashboard/routes/nginx.js +22 -146
- package/src/dashboard/routes/processes.js +29 -0
- package/src/dashboard/routes/settings.js +25 -232
- package/src/dashboard/routes/ssl.js +18 -276
- package/src/dashboard/server.js +279 -165
- package/src/dashboard/socketManager.js +246 -0
- package/src/dashboard/views/index.ejs +1 -0
- package/src/dashboard/views/partials/domain-form.ejs +64 -1
- package/src/dashboard/views/partials/login.ejs +69 -8
- package/src/dashboard/views/partials/processes-panel.ejs +261 -0
- package/src/dashboard/views/partials/settings-panel.ejs +549 -118
- package/src/dashboard/views/partials/sidebar.ejs +3 -1
- package/src/dashboard/lib/domains-db.js +0 -51
- /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
|
@@ -0,0 +1,364 @@
|
|
|
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
|
+
* @property {Object|null} nextState - The state to record once the send succeeds
|
|
224
|
+
*/
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Decides whether a transition is worth notifying about.
|
|
228
|
+
*
|
|
229
|
+
* PURE: this records nothing. It used to write "notified" to the database
|
|
230
|
+
* before the notification was sent, which made a failed send invisible — the
|
|
231
|
+
* state already claimed it had gone out, so it was never retried.
|
|
232
|
+
*
|
|
233
|
+
* The caller now does: evaluate -> claim -> send -> commit, and releases the
|
|
234
|
+
* claim if the send fails. See core/notifications/claim.js and
|
|
235
|
+
* core/notifications/dispatch.js.
|
|
236
|
+
*
|
|
237
|
+
* nextState is what commitNotification() should persist. It is returned even
|
|
238
|
+
* when shouldNotify is false, because the first sighting of a domain still has
|
|
239
|
+
* to be recorded — it just must not produce a notification.
|
|
240
|
+
*
|
|
241
|
+
* @param {string|null} domain - null for global events
|
|
242
|
+
* @param {string} eventType
|
|
243
|
+
* @param {string} currentStatus - 'up' or 'down'
|
|
244
|
+
* @returns {NotificationDecision}
|
|
245
|
+
*/
|
|
246
|
+
export function evaluateTransition(domain, eventType, currentStatus) {
|
|
247
|
+
const previousState = getNotificationState(domain, eventType);
|
|
248
|
+
const previousNotifiedFor = previousState.notifiedFor;
|
|
249
|
+
|
|
250
|
+
const status = currentStatus === 'up' || currentStatus === 'down' ? currentStatus : 'unknown';
|
|
251
|
+
|
|
252
|
+
// First time seeing this domain/event: record it, never notify. Otherwise
|
|
253
|
+
// every restart would announce everything as newly down.
|
|
254
|
+
if (previousNotifiedFor === null || previousState.status === 'unknown') {
|
|
255
|
+
return {
|
|
256
|
+
shouldNotify: false,
|
|
257
|
+
reason: 'first_check',
|
|
258
|
+
currentStatus: status,
|
|
259
|
+
previousNotifiedFor: null,
|
|
260
|
+
nextState: { status, lastNotifiedAt: null, notifiedFor: status },
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (previousNotifiedFor === status) {
|
|
265
|
+
return {
|
|
266
|
+
shouldNotify: false,
|
|
267
|
+
reason: 'no_change',
|
|
268
|
+
currentStatus: status,
|
|
269
|
+
previousNotifiedFor,
|
|
270
|
+
nextState: null,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (status === 'down' && previousNotifiedFor !== 'down') {
|
|
275
|
+
return {
|
|
276
|
+
shouldNotify: true,
|
|
277
|
+
reason: 'state_changed',
|
|
278
|
+
currentStatus: 'down',
|
|
279
|
+
previousNotifiedFor,
|
|
280
|
+
nextState: { status: 'down', lastNotifiedAt: null, notifiedFor: 'down' },
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (status === 'up' && previousNotifiedFor === 'down') {
|
|
285
|
+
return {
|
|
286
|
+
shouldNotify: true,
|
|
287
|
+
reason: 'recovery',
|
|
288
|
+
currentStatus: 'up',
|
|
289
|
+
previousNotifiedFor: 'down',
|
|
290
|
+
nextState: { status: 'up', lastNotifiedAt: null, notifiedFor: 'up' },
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// status is 'unknown', or an up->up with a stale notifiedFor. Record the
|
|
295
|
+
// status so the next real transition is judged against the truth, but say
|
|
296
|
+
// nothing: there is no event here a user would want to hear about.
|
|
297
|
+
return {
|
|
298
|
+
shouldNotify: false,
|
|
299
|
+
reason: 'edge_case',
|
|
300
|
+
currentStatus: status,
|
|
301
|
+
previousNotifiedFor,
|
|
302
|
+
nextState: { status, lastNotifiedAt: null, notifiedFor: status },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Records a decision as sent.
|
|
308
|
+
*
|
|
309
|
+
* Call this ONLY after the notification actually went out. The timestamp is
|
|
310
|
+
* stamped here rather than in evaluateTransition(), so lastNotifiedAt always
|
|
311
|
+
* means "when it was really delivered".
|
|
312
|
+
*
|
|
313
|
+
* @param {string|null} domain
|
|
314
|
+
* @param {string} eventType
|
|
315
|
+
* @param {NotificationDecision} decision
|
|
316
|
+
* @param {number} [sentAt]
|
|
317
|
+
*/
|
|
318
|
+
export function commitNotification(domain, eventType, decision, sentAt = Date.now()) {
|
|
319
|
+
if (!decision?.nextState) return;
|
|
320
|
+
|
|
321
|
+
setNotificationState(domain, eventType, {
|
|
322
|
+
...decision.nextState,
|
|
323
|
+
lastNotifiedAt: decision.shouldNotify ? sentAt : decision.nextState.lastNotifiedAt,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Evaluate and record in one step, with no send in between.
|
|
329
|
+
*
|
|
330
|
+
* Retained for callers that only track state and never notify. It is NOT the
|
|
331
|
+
* path the monitors use: anything that sends must evaluate, claim, send and
|
|
332
|
+
* then commit, so a failed send is retried.
|
|
333
|
+
*
|
|
334
|
+
* @param {string|null} domain
|
|
335
|
+
* @param {string} eventType
|
|
336
|
+
* @param {string} currentStatus
|
|
337
|
+
* @returns {NotificationDecision}
|
|
338
|
+
*/
|
|
339
|
+
export function shouldSendNotification(domain, eventType, currentStatus) {
|
|
340
|
+
const decision = evaluateTransition(domain, eventType, currentStatus);
|
|
341
|
+
commitNotification(domain, eventType, decision);
|
|
342
|
+
return decision;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Clear notification state for a domain (useful for testing or manual reset).
|
|
347
|
+
* @param {string|null} domain - null to clear global state, or specific domain
|
|
348
|
+
* @param {string} eventType
|
|
349
|
+
*/
|
|
350
|
+
export function clearNotificationState(domain, eventType) {
|
|
351
|
+
const key = domain ? `${domain}:${eventType}` : `global:${eventType}`;
|
|
352
|
+
const map = getNotificationStateMap();
|
|
353
|
+
delete map[key];
|
|
354
|
+
saveNotificationStateMap(map);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Clear all notification state (useful for testing).
|
|
359
|
+
*/
|
|
360
|
+
export function clearAllNotificationState() {
|
|
361
|
+
dbSet(STATE_DB_KEY, {});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export { KNOWN_EVENT_TYPES };
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { dbGet, dbSet } from './db.js';
|
|
4
|
+
import { DOMAIN_DEFAULTS, migrateDomain } from './nginx-conf-generator.js';
|
|
5
|
+
import { writeConfWithTest } from './nginx-apply.js';
|
|
6
|
+
import { run } from './shell.js';
|
|
7
|
+
import { loadConfig } from './config.js';
|
|
8
|
+
import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk } from './platform.js';
|
|
9
|
+
import { saveDomainNotifConfig } from './domainNotifier.js';
|
|
10
|
+
import { bumpHubRevision } from './hubLink.js';
|
|
11
|
+
|
|
12
|
+
// Re-export DOMAIN_DEFAULTS for consumers
|
|
13
|
+
export { DOMAIN_DEFAULTS, migrateDomain };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Get all domains, applying v2 migration to each record.
|
|
17
|
+
* @returns {Array} Array of domain objects (v2 schema)
|
|
18
|
+
*/
|
|
19
|
+
export function getDomains() {
|
|
20
|
+
const raw = dbGet('domains') ?? [];
|
|
21
|
+
return raw.map(migrateDomain);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Save domains array to storage.
|
|
26
|
+
* @param {Array} arr - Array of domain objects
|
|
27
|
+
*/
|
|
28
|
+
export function saveDomains(arr) {
|
|
29
|
+
dbSet('domains', arr);
|
|
30
|
+
|
|
31
|
+
// Every domain write goes through here — dashboard, CLI and hub alike — so
|
|
32
|
+
// this is the one place that can tell the agent "something changed". The
|
|
33
|
+
// agent polls the counter every few seconds and pushes only when it moves,
|
|
34
|
+
// which is what gets CLI-side edits to the Hub in seconds instead of
|
|
35
|
+
// waiting for the 5-minute config heartbeat.
|
|
36
|
+
try {
|
|
37
|
+
bumpHubRevision();
|
|
38
|
+
} catch { /* never block a domain save on hub bookkeeping */ }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Find a domain by name.
|
|
43
|
+
* @param {string} name - Domain name to find
|
|
44
|
+
* @returns {Object|undefined} Domain object or undefined
|
|
45
|
+
*/
|
|
46
|
+
export function findDomain(name) {
|
|
47
|
+
return getDomains().find((d) => d.name === name);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Create a new domain object with defaults merged.
|
|
52
|
+
* @param {Object} partial - Partial domain data
|
|
53
|
+
* @returns {Object} Complete domain object with defaults
|
|
54
|
+
*/
|
|
55
|
+
export function createDomain(partial) {
|
|
56
|
+
const now = new Date().toISOString();
|
|
57
|
+
return {
|
|
58
|
+
...DOMAIN_DEFAULTS,
|
|
59
|
+
...partial,
|
|
60
|
+
ssl: { ...DOMAIN_DEFAULTS.ssl, ...partial.ssl },
|
|
61
|
+
performance: { ...DOMAIN_DEFAULTS.performance, ...partial.performance },
|
|
62
|
+
security: { ...DOMAIN_DEFAULTS.security, ...partial.security },
|
|
63
|
+
advanced: { ...DOMAIN_DEFAULTS.advanced, ...partial.advanced },
|
|
64
|
+
configFile: null,
|
|
65
|
+
createdAt: now,
|
|
66
|
+
updatedAt: now,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ─── Hub command handler ───────────────────────────────────────────────────────
|
|
71
|
+
// Called by hubAgent when the hub dispatches a hub:manageDomain event.
|
|
72
|
+
// Payload shape: { action: 'create'|'update'|'delete'|'toggle'|'reload', name?, domain? }
|
|
73
|
+
|
|
74
|
+
export async function handleHubDomainCommand(payload) {
|
|
75
|
+
const { action, name, domain, deleteCert } = payload ?? {};
|
|
76
|
+
const { nginxDir } = loadConfig();
|
|
77
|
+
|
|
78
|
+
switch (action) {
|
|
79
|
+
|
|
80
|
+
case 'create': {
|
|
81
|
+
if (!domain?.name) return { ok: false, error: 'domain.name is required' };
|
|
82
|
+
if (findDomain(domain.name)) return { ok: false, error: `Domain ${domain.name} already exists` };
|
|
83
|
+
|
|
84
|
+
const newDomain = createDomain({
|
|
85
|
+
name: domain.name,
|
|
86
|
+
port: Number(domain.port) || 3000,
|
|
87
|
+
backendHost: domain.backendHost ?? DOMAIN_DEFAULTS.backendHost,
|
|
88
|
+
upstreamType: domain.upstreamType ?? DOMAIN_DEFAULTS.upstreamType,
|
|
89
|
+
www: domain.www ?? false,
|
|
90
|
+
wildcard: domain.wildcard ?? false,
|
|
91
|
+
enabled: true,
|
|
92
|
+
ssl: { ...DOMAIN_DEFAULTS.ssl, ...domain.ssl },
|
|
93
|
+
performance: { ...DOMAIN_DEFAULTS.performance, ...domain.performance },
|
|
94
|
+
security: { ...DOMAIN_DEFAULTS.security, ...domain.security },
|
|
95
|
+
advanced: { ...DOMAIN_DEFAULTS.advanced, ...domain.advanced },
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// Shared core apply (same path as the CLI and the dashboard API).
|
|
99
|
+
const created = await writeConfWithTest(newDomain);
|
|
100
|
+
if (!created.ok) {
|
|
101
|
+
return { ok: false, error: created.error ?? 'nginx rejected the new config' };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const domains = getDomains();
|
|
105
|
+
domains.push(newDomain);
|
|
106
|
+
saveDomains(domains);
|
|
107
|
+
|
|
108
|
+
if (domain.notifications && typeof domain.notifications === 'object') {
|
|
109
|
+
try { saveDomainNotifConfig(domain.name, domain.notifications); } catch { /* non-fatal */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
bumpHubRevision();
|
|
113
|
+
console.log('[hubAgent] domain created:', domain.name);
|
|
114
|
+
return { ok: true, action: 'create', domain: domain.name };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
case 'update': {
|
|
118
|
+
const targetName = name ?? domain?.name;
|
|
119
|
+
const existing = targetName ? findDomain(targetName) : null;
|
|
120
|
+
if (!existing) return { ok: false, error: `Domain ${targetName} not found` };
|
|
121
|
+
|
|
122
|
+
const updates = domain ?? {};
|
|
123
|
+
const updatedDomain = {
|
|
124
|
+
...existing,
|
|
125
|
+
...updates,
|
|
126
|
+
name: existing.name, // name is immutable
|
|
127
|
+
ssl: { ...existing.ssl, ...updates.ssl },
|
|
128
|
+
performance: { ...existing.performance, ...updates.performance },
|
|
129
|
+
security: { ...existing.security, ...updates.security },
|
|
130
|
+
advanced: { ...existing.advanced, ...updates.advanced },
|
|
131
|
+
updatedAt: new Date().toISOString(),
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
// Shared core apply — restores the previous config exactly if it fails,
|
|
135
|
+
// so the .bak dance is no longer needed here.
|
|
136
|
+
const updatedResult = await writeConfWithTest(updatedDomain);
|
|
137
|
+
if (!updatedResult.ok) {
|
|
138
|
+
return { ok: false, error: updatedResult.error ?? 'nginx rejected the updated config' };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const domains = getDomains();
|
|
142
|
+
const idx = domains.findIndex((d) => d.name === existing.name);
|
|
143
|
+
domains[idx] = updatedDomain;
|
|
144
|
+
saveDomains(domains);
|
|
145
|
+
|
|
146
|
+
if (updates.notifications && typeof updates.notifications === 'object') {
|
|
147
|
+
try { saveDomainNotifConfig(existing.name, updates.notifications); } catch { /* non-fatal */ }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
bumpHubRevision();
|
|
151
|
+
console.log('[hubAgent] domain updated:', existing.name);
|
|
152
|
+
return { ok: true, action: 'update', domain: existing.name };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
case 'delete': {
|
|
156
|
+
const domain = findDomain(name);
|
|
157
|
+
if (!domain) return { ok: false, error: `Domain ${name} not found` };
|
|
158
|
+
|
|
159
|
+
if (domain.configFile) {
|
|
160
|
+
try { await fs.unlink(domain.configFile); } catch (err) {
|
|
161
|
+
if (err.code !== 'ENOENT') return { ok: false, error: `Could not remove config: ${err.message}` };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
saveDomains(getDomains().filter((d) => d.name !== name));
|
|
166
|
+
|
|
167
|
+
// Optionally delete SSL certificate directory
|
|
168
|
+
if (deleteCert && domain.ssl?.enabled) {
|
|
169
|
+
const { sslDir } = loadConfig();
|
|
170
|
+
const certDir = path.join(sslDir, name);
|
|
171
|
+
try { await fs.rm(certDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
console.log('[hubAgent] domain deleted:', name);
|
|
175
|
+
|
|
176
|
+
// Reload nginx so the deleted domain stops being served
|
|
177
|
+
await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
|
|
178
|
+
bumpHubRevision();
|
|
179
|
+
return { ok: true, action: 'delete', domain: name };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
case 'toggle': {
|
|
183
|
+
const domain = findDomain(name);
|
|
184
|
+
if (!domain) return { ok: false, error: `Domain ${name} not found` };
|
|
185
|
+
|
|
186
|
+
const isEnabled = domain.enabled !== false;
|
|
187
|
+
const confPath = domain.configFile;
|
|
188
|
+
if (!confPath) return { ok: false, error: `Domain ${name} has no config file` };
|
|
189
|
+
|
|
190
|
+
const basePath = confPath.replace(/\.disabled$/, '');
|
|
191
|
+
const enabledPath = basePath;
|
|
192
|
+
const disabledPath = `${basePath}.disabled`;
|
|
193
|
+
|
|
194
|
+
if (isEnabled) {
|
|
195
|
+
try { await fs.rename(enabledPath, disabledPath); } catch (err) {
|
|
196
|
+
return { ok: false, error: `Could not disable: ${err.message}` };
|
|
197
|
+
}
|
|
198
|
+
const domains = getDomains();
|
|
199
|
+
const idx = domains.findIndex((d) => d.name === name);
|
|
200
|
+
domains[idx] = { ...domain, enabled: false, configFile: disabledPath, updatedAt: new Date().toISOString() };
|
|
201
|
+
saveDomains(domains);
|
|
202
|
+
} else {
|
|
203
|
+
try { await fs.rename(disabledPath, enabledPath); } catch (err) {
|
|
204
|
+
return { ok: false, error: `Could not enable: ${err.message}` };
|
|
205
|
+
}
|
|
206
|
+
const testResult = await run(isWindows ? nginxTestCmd(nginxDir) : 'nginx -t', { cwd: nginxDir });
|
|
207
|
+
if (!isNginxTestOk(testResult)) {
|
|
208
|
+
await fs.rename(enabledPath, disabledPath).catch(() => {});
|
|
209
|
+
return { ok: false, error: 'nginx rejected the config after enabling' };
|
|
210
|
+
}
|
|
211
|
+
const domains = getDomains();
|
|
212
|
+
const idx = domains.findIndex((d) => d.name === name);
|
|
213
|
+
domains[idx] = { ...domain, enabled: true, configFile: enabledPath, updatedAt: new Date().toISOString() };
|
|
214
|
+
saveDomains(domains);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
|
|
218
|
+
bumpHubRevision();
|
|
219
|
+
console.log('[hubAgent] domain toggled:', name, '→', !isEnabled);
|
|
220
|
+
return { ok: true, action: 'toggle', domain: name, enabled: !isEnabled };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
case 'reload': {
|
|
224
|
+
const testResult = await run(isWindows ? nginxTestCmd(nginxDir) : 'nginx -t', { cwd: nginxDir });
|
|
225
|
+
if (!isNginxTestOk(testResult)) return { ok: false, error: 'nginx config test failed' };
|
|
226
|
+
await run(isWindows ? nginxReloadCmd(nginxDir) : 'sudo -n /usr/bin/systemctl reload nginx', { cwd: nginxDir });
|
|
227
|
+
console.log('[hubAgent] nginx reloaded for domain:', name);
|
|
228
|
+
return { ok: true, action: 'reload', domain: name };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
default:
|
|
232
|
+
return { ok: false, error: `Unknown domain action: ${action}` };
|
|
233
|
+
}
|
|
234
|
+
}
|