easy-devops 1.2.1 → 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.
Files changed (126) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-B6zdwEnG.css +1 -0
  3. package/dist/ui/assets/index-Cy0oNmul.js +442 -0
  4. package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
  5. package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
  6. package/dist/ui/brand/apple-touch-icon.png +0 -0
  7. package/dist/ui/brand/favicon-16.png +0 -0
  8. package/dist/ui/brand/favicon-32.png +0 -0
  9. package/dist/ui/brand/favicon-light-16.png +0 -0
  10. package/dist/ui/brand/favicon-light-32.png +0 -0
  11. package/dist/ui/brand/favicon.ico +0 -0
  12. package/dist/ui/brand/icon-192.png +0 -0
  13. package/dist/ui/brand/icon-48.png +0 -0
  14. package/dist/ui/brand/icon-512.png +0 -0
  15. package/dist/ui/brand/icon-64-light.png +0 -0
  16. package/dist/ui/brand/icon-64.png +0 -0
  17. package/dist/ui/brand/logo-dark.png +0 -0
  18. package/dist/ui/brand/logo-light.png +0 -0
  19. package/dist/ui/brand/mark-dark.png +0 -0
  20. package/dist/ui/brand/mark-light.png +0 -0
  21. package/dist/ui/index.html +71 -0
  22. package/install.ps1 +188 -1
  23. package/install.sh +254 -29
  24. package/package.json +15 -4
  25. package/src/cli/dash.js +110 -0
  26. package/src/cli/index.js +237 -106
  27. package/src/cli/managers/domain-manager.js +60 -40
  28. package/src/cli/managers/ssl-manager.js +47 -330
  29. package/src/cli/menu.js +156 -0
  30. package/src/cli/menus/cleanup.js +205 -0
  31. package/src/cli/menus/dashboard.js +92 -1
  32. package/src/cli/menus/runtime.js +236 -0
  33. package/src/cli/menus/service.js +764 -0
  34. package/src/cli/menus/settings.js +176 -8
  35. package/src/cli/menus/uninstall.js +167 -0
  36. package/src/cli/menus/update.js +221 -65
  37. package/src/core/acme-challenge.js +273 -0
  38. package/src/core/cert-operations.js +189 -0
  39. package/src/{dashboard/lib → core}/cert-reader.js +2 -2
  40. package/src/core/cert-renewal.js +494 -0
  41. package/src/core/cleanup.js +600 -0
  42. package/src/core/config.js +169 -2
  43. package/src/core/daemon/ipc.js +292 -0
  44. package/src/core/daemon/lock.js +294 -0
  45. package/src/core/daemon/run.js +241 -0
  46. package/src/core/daemon/stopRequest.js +162 -0
  47. package/src/core/db.js +37 -8
  48. package/src/core/deploy/apps.js +491 -0
  49. package/src/core/deploy/domainLink.js +200 -0
  50. package/src/core/deploy/engine.js +973 -0
  51. package/src/core/deploy/ezfile.js +361 -0
  52. package/src/core/deploy/github.js +239 -0
  53. package/src/core/deploy/githubApi.js +261 -0
  54. package/src/core/deploy/hookServer.js +325 -0
  55. package/src/core/deploy/hubCommands.js +267 -0
  56. package/src/core/deploy/launcher.js +57 -0
  57. package/src/core/deploy/status.js +91 -0
  58. package/src/core/deploy/store.js +398 -0
  59. package/src/core/domainNotifier.js +94 -28
  60. package/src/core/domains-db.js +234 -0
  61. package/src/core/events.js +94 -2
  62. package/src/core/hub/agent.js +842 -0
  63. package/src/core/hubLink.js +306 -0
  64. package/src/core/hubPermissions.js +430 -0
  65. package/src/core/installSource.js +162 -0
  66. package/src/core/jobs/bus.js +120 -0
  67. package/src/core/jobs/index.js +371 -0
  68. package/src/core/jobs/monitors.js +368 -0
  69. package/src/core/jobs/owner.js +217 -0
  70. package/src/core/jobs/revisionWatcher.js +106 -0
  71. package/src/core/nginx-apply.js +213 -0
  72. package/src/core/nginx-conf-generator.js +253 -17
  73. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  74. package/src/core/notifications/claim.js +214 -0
  75. package/src/core/notifications/dispatch.js +154 -0
  76. package/src/core/notifier.js +31 -1
  77. package/src/core/passwords.js +172 -0
  78. package/src/core/permissions.js +8 -4
  79. package/src/core/platform.js +709 -2
  80. package/src/core/probeCache.js +258 -0
  81. package/src/core/purge.js +372 -0
  82. package/src/core/runner.js +488 -0
  83. package/src/core/service/acl.js +226 -0
  84. package/src/core/service/dataDir.js +345 -0
  85. package/src/core/service/index.js +1128 -0
  86. package/src/core/service/legacy.js +218 -0
  87. package/src/core/service/runtime.js +446 -0
  88. package/src/core/service/runtimeUpdate.js +800 -0
  89. package/src/core/service/systemd.js +458 -0
  90. package/src/core/service/windowsPersonal.js +530 -0
  91. package/src/core/service/windowsService.js +576 -0
  92. package/src/core/service/winsw.js +260 -0
  93. package/src/core/setupCode.js +331 -0
  94. package/src/core/shell.js +70 -7
  95. package/src/core/ssl-issuer.js +627 -0
  96. package/src/core/updater.js +295 -0
  97. package/src/core/validators.js +99 -0
  98. package/src/dashboard/controllers/authController.js +302 -15
  99. package/src/dashboard/controllers/deploymentsController.js +479 -0
  100. package/src/dashboard/controllers/domainsController.js +39 -52
  101. package/src/dashboard/controllers/hubController.js +135 -0
  102. package/src/dashboard/controllers/nginxController.js +21 -3
  103. package/src/dashboard/controllers/processesController.js +368 -0
  104. package/src/dashboard/controllers/settingsController.js +180 -12
  105. package/src/dashboard/controllers/sslController.js +171 -10
  106. package/src/dashboard/lib/daemonBridge.js +163 -0
  107. package/src/dashboard/lib/localRequest.js +235 -0
  108. package/src/dashboard/lib/loginRateLimit.js +119 -0
  109. package/src/dashboard/lib/requireAuth.js +80 -0
  110. package/src/dashboard/public/js/app.js +489 -19
  111. package/src/dashboard/routes/auth.js +10 -10
  112. package/src/dashboard/routes/deployments.js +46 -0
  113. package/src/dashboard/routes/domains.js +9 -0
  114. package/src/dashboard/routes/hub.js +22 -0
  115. package/src/dashboard/routes/nginx.js +9 -0
  116. package/src/dashboard/routes/processes.js +29 -0
  117. package/src/dashboard/routes/settings.js +9 -0
  118. package/src/dashboard/routes/ssl.js +9 -0
  119. package/src/dashboard/server.js +288 -21
  120. package/src/dashboard/socketManager.js +171 -207
  121. package/src/dashboard/views/index.ejs +1 -0
  122. package/src/dashboard/views/partials/login.ejs +68 -7
  123. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  124. package/src/dashboard/views/partials/settings-panel.ejs +287 -0
  125. package/src/dashboard/views/partials/sidebar.ejs +2 -0
  126. package/src/dashboard/lib/domains-db.js +0 -51
@@ -0,0 +1,214 @@
1
+ /**
2
+ * core/notifications/claim.js
3
+ *
4
+ * Makes sure exactly one process sends a given notification, even while the
5
+ * daemon and an open dashboard are both briefly running the monitors.
6
+ *
7
+ * ── The ordering that matters ───────────────────────────────────────────────
8
+ *
9
+ * The old code marked a transition "notified" BEFORE sending it. That made a
10
+ * lost notification invisible: if the webhook failed, the state already said
11
+ * it had been sent, so it was never retried. The order here is:
12
+ *
13
+ * 1. claim the transition (atomic; exactly one process wins)
14
+ * 2. send
15
+ * 3. commit — only now is it recorded as sent
16
+ *
17
+ * and on a send failure the claim is RELEASED without committing, so the next
18
+ * poll tries again.
19
+ *
20
+ * ── Why the claim is a file and not a database row ──────────────────────────
21
+ *
22
+ * It has to be atomic across processes, and `good.db` exposes only get/set
23
+ * through `core/db.js` — no compare-and-swap. The obvious substitute, "write
24
+ * my pid then read it back and see if I won", is not safe: two processes can
25
+ * interleave write/read/write/read and both see their own pid.
26
+ *
27
+ * `open(path, 'wx')` is a single atomic syscall on both platforms: it creates
28
+ * the file or fails with EEXIST, and it cannot do both. So the claim lives in
29
+ * the data directory next to the database, while the durable "was it sent"
30
+ * record stays in the database where it belongs. Raw SQL would be the other
31
+ * way to get a real CAS, and the constitution prohibits it.
32
+ *
33
+ * ── Crashed claimants ──────────────────────────────────────────────────────
34
+ *
35
+ * A process that dies between claiming and committing must not block the
36
+ * transition for ever. A claim older than CLAIM_TTL_MS whose owner is gone is
37
+ * taken over. Both conditions, for the same reason as the daemon lock: a live
38
+ * pid may still be working, and a stale timestamp alone can mean a slow send.
39
+ */
40
+
41
+ import fs from 'fs';
42
+ import path from 'path';
43
+ import { getDataDir } from '../platform.js';
44
+ import { isPidAlive } from '../daemon/lock.js';
45
+
46
+ /**
47
+ * How long a claim may be held before another process may take it over.
48
+ *
49
+ * Generous on purpose: a Telegram or Discord call can legitimately take tens
50
+ * of seconds, and taking a claim away from a sender that is still working is
51
+ * how duplicates happen.
52
+ */
53
+ export const CLAIM_TTL_MS = 120_000;
54
+
55
+ const CLAIM_DIR = 'claims';
56
+
57
+ /** Directory holding claim files. */
58
+ export function claimDir(dataDir = getDataDir()) {
59
+ return path.join(dataDir, CLAIM_DIR);
60
+ }
61
+
62
+ /**
63
+ * Turns a transition into a safe file name.
64
+ *
65
+ * Domain names, event types and statuses are concatenated, so anything that is
66
+ * not plainly safe in a path is replaced. The result is also length-capped,
67
+ * because a long wildcard domain plus an event type can otherwise exceed the
68
+ * filename limit and fail the claim for a reason that has nothing to do with
69
+ * contention.
70
+ *
71
+ * @param {string|null} domain
72
+ * @param {string} eventType
73
+ * @param {string} status
74
+ * @returns {string}
75
+ */
76
+ export function claimKey(domain, eventType, status) {
77
+ const parts = [domain ?? '_global', eventType, status]
78
+ .map((p) => String(p).replace(/[^a-zA-Z0-9._-]/g, '_'))
79
+ .join('__');
80
+ return parts.slice(0, 180);
81
+ }
82
+
83
+ /** Absolute path of one claim. */
84
+ export function claimPath(domain, eventType, status, dataDir = getDataDir()) {
85
+ return path.join(claimDir(dataDir), `${claimKey(domain, eventType, status)}.claim`);
86
+ }
87
+
88
+ /**
89
+ * Reads a claim file.
90
+ * @returns {{ pid: number, at: number }|null}
91
+ */
92
+ function readClaim(file) {
93
+ try {
94
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
95
+ return { pid: Number(parsed?.pid) || 0, at: Number(parsed?.at) || 0 };
96
+ } catch {
97
+ // Unreadable or half-written: treat as a claim with no useful owner, so
98
+ // the TTL path below can reclaim it rather than blocking for ever.
99
+ return { pid: 0, at: 0 };
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Tries to become the one process that sends this notification.
105
+ *
106
+ * @param {Object} opts
107
+ * @param {string|null} opts.domain
108
+ * @param {string} opts.eventType
109
+ * @param {string} opts.status
110
+ * @param {string} [opts.dataDir]
111
+ * @param {number} [opts.now] Injectable clock, for tests
112
+ * @returns {{ ok: true, takeover: boolean, commit: () => void, release: () => void }
113
+ * | { ok: false, heldBy: number|null, reason: string }}
114
+ */
115
+ export function claim({
116
+ domain,
117
+ eventType,
118
+ status,
119
+ dataDir = getDataDir(),
120
+ now = Date.now(),
121
+ } = {}) {
122
+ const file = claimPath(domain, eventType, status, dataDir);
123
+ const payload = `${JSON.stringify({ pid: process.pid, at: now })}\n`;
124
+
125
+ const finish = (takeover) => ({
126
+ ok: true,
127
+ takeover,
128
+ /** Removes the claim. Called after the send succeeded AND was recorded. */
129
+ commit: () => { try { fs.unlinkSync(file); } catch { /* already gone */ } },
130
+ /** Removes the claim WITHOUT recording a send, so it is retried. */
131
+ release: () => { try { fs.unlinkSync(file); } catch { /* already gone */ } },
132
+ });
133
+
134
+ try {
135
+ fs.mkdirSync(claimDir(dataDir), { recursive: true });
136
+ } catch { /* created concurrently, or unwritable — the open below reports it */ }
137
+
138
+ // The atomic step: creates or fails, never both.
139
+ try {
140
+ fs.writeFileSync(file, payload, { flag: 'wx', encoding: 'utf8', mode: 0o600 });
141
+ return finish(false);
142
+ } catch (err) {
143
+ if (err?.code !== 'EEXIST') {
144
+ return { ok: false, heldBy: null, reason: `could not write a claim: ${err.message}` };
145
+ }
146
+ }
147
+
148
+ // Someone holds it. Take it over only if they are gone AND it is old.
149
+ const held = readClaim(file);
150
+ const age = now - held.at;
151
+ const ownerGone = held.pid === 0 || !isPidAlive(held.pid);
152
+
153
+ if (!ownerGone) {
154
+ return { ok: false, heldBy: held.pid, reason: `pid ${held.pid} is sending it` };
155
+ }
156
+ if (age < CLAIM_TTL_MS) {
157
+ return {
158
+ ok: false,
159
+ heldBy: held.pid || null,
160
+ reason: `claim is ${Math.round(age / 1000)}s old; waiting for the ${Math.round(CLAIM_TTL_MS / 1000)}s timeout`,
161
+ };
162
+ }
163
+
164
+ // Abandoned. Replace it, and re-check that we are the one who did: two
165
+ // processes can reach this point together, and only the one whose pid is in
166
+ // the file afterwards may proceed.
167
+ try {
168
+ fs.writeFileSync(file, payload, { encoding: 'utf8', mode: 0o600 });
169
+ } catch (err) {
170
+ return { ok: false, heldBy: held.pid || null, reason: `could not take over the claim: ${err.message}` };
171
+ }
172
+
173
+ const after = readClaim(file);
174
+ if (after.pid !== process.pid) {
175
+ return { ok: false, heldBy: after.pid, reason: `pid ${after.pid} took over first` };
176
+ }
177
+
178
+ return finish(true);
179
+ }
180
+
181
+ /**
182
+ * Removes every claim owned by a dead process.
183
+ *
184
+ * Called when a job owner starts up: a crash leaves claims behind, and clearing
185
+ * the ones whose owners are gone means the first poll after a restart can send
186
+ * rather than waiting out the TTL.
187
+ *
188
+ * @returns {number} How many were removed
189
+ */
190
+ export function sweepAbandoned({ dataDir = getDataDir(), now = Date.now() } = {}) {
191
+ let removed = 0;
192
+ let entries;
193
+ try {
194
+ entries = fs.readdirSync(claimDir(dataDir));
195
+ } catch {
196
+ return 0;
197
+ }
198
+
199
+ for (const name of entries) {
200
+ if (!name.endsWith('.claim')) continue;
201
+ const file = path.join(claimDir(dataDir), name);
202
+ const held = readClaim(file);
203
+
204
+ const ownerGone = held.pid === 0 || !isPidAlive(held.pid);
205
+ if (!ownerGone) continue;
206
+ // Still honour the TTL: a claim written microseconds ago by a process that
207
+ // has not yet appeared in the process table would otherwise be swept.
208
+ if (now - held.at < CLAIM_TTL_MS) continue;
209
+
210
+ try { fs.unlinkSync(file); removed++; } catch { /* raced */ }
211
+ }
212
+
213
+ return removed;
214
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * core/notifications/dispatch.js
3
+ *
4
+ * The one correct way to send a state-transition notification.
5
+ *
6
+ * Everything that monitors a domain or nginx goes through here, because the
7
+ * ordering is easy to get wrong and the failure is silent when you do: the old
8
+ * code recorded "notified" before sending, so a webhook that was down meant the
9
+ * user simply never heard about an outage.
10
+ *
11
+ * The order, and why each step is where it is:
12
+ *
13
+ * 1. evaluate — is this a real transition? (pure; records nothing)
14
+ * 2. claim — atomically become the only process sending it
15
+ * 3. send — the actual channels
16
+ * 4. commit — record it as sent, THEN drop the claim
17
+ *
18
+ * On a send failure step 4 is skipped and the claim is released, so the next
19
+ * poll evaluates the same transition again and retries it.
20
+ *
21
+ * Commit before release matters: if the process dies between them, the worst
22
+ * case is a claim file left behind that the TTL sweep clears. Releasing first
23
+ * would risk another process re-sending something already recorded as sent.
24
+ *
25
+ * A transition that needs no notification (no change, first sighting) never
26
+ * takes a claim — contention on the claim file would otherwise be constant,
27
+ * since the common case is "nothing happened".
28
+ */
29
+
30
+ import {
31
+ evaluateTransition,
32
+ commitNotification,
33
+ getEffectiveChannelIds,
34
+ getAllDomainChannelIds,
35
+ } from '../domainNotifier.js';
36
+ import { sendNotification } from '../notifier.js';
37
+ import { claim } from './claim.js';
38
+
39
+ /**
40
+ * @typedef {Object} DispatchResult
41
+ * @property {boolean} sent Whether a notification actually went out
42
+ * @property {string} reason Why, in a form a log line can use
43
+ * @property {Object} decision The evaluateTransition() result
44
+ * @property {Object|null} event The event that was emitted, if any
45
+ * @property {Object|null} send The sendNotification() result, if it was tried
46
+ * @property {boolean} claimed Whether this process won the claim
47
+ */
48
+
49
+ /**
50
+ * Evaluates a transition and, if it is worth announcing, sends it exactly once
51
+ * across every process sharing this data directory.
52
+ *
53
+ * @param {Object} opts
54
+ * @param {string|null} opts.domain null for global events
55
+ * @param {string} opts.eventType e.g. 'nginx_down', 'domain_health'
56
+ * @param {string} opts.status 'up' | 'down'
57
+ * @param {(decision: Object) => Object} opts.buildEvent
58
+ * Builds the event from the decision. Called only when something will be
59
+ * sent, so the caller does not pay for an event nobody sees.
60
+ * @param {(event: Object) => void} [opts.emitLocal]
61
+ * Pushes the event to connected dashboards. Called only by the process
62
+ * that won the claim, for the same no-duplicates reason as the channels.
63
+ * @param {string[]} [opts.channelIds] Overrides channel resolution
64
+ * @param {string} [opts.dataDir]
65
+ * @param {Function} [opts.send] Injectable, for tests
66
+ * @returns {Promise<DispatchResult>}
67
+ */
68
+ export async function dispatchTransition({
69
+ domain,
70
+ eventType,
71
+ status,
72
+ buildEvent,
73
+ emitLocal = null,
74
+ channelIds = null,
75
+ dataDir = undefined,
76
+ send = sendNotification,
77
+ } = {}) {
78
+ const decision = evaluateTransition(domain, eventType, status);
79
+
80
+ if (!decision.shouldNotify) {
81
+ // Still record the status: a first sighting has to be remembered or every
82
+ // poll treats itself as the first. No claim is needed because no
83
+ // notification goes out, and the write is idempotent.
84
+ commitNotification(domain, eventType, decision);
85
+ return { sent: false, reason: decision.reason, decision, event: null, send: null, claimed: false };
86
+ }
87
+
88
+ const held = claim({ domain, eventType, status: decision.currentStatus, dataDir });
89
+ if (!held.ok) {
90
+ // Another process is sending it. Record nothing at all: the winner commits
91
+ // the state, and writing it here would mask a failure over there.
92
+ return { sent: false, reason: `another process has it: ${held.reason}`, decision, event: null, send: null, claimed: false };
93
+ }
94
+
95
+ const event = buildEvent(decision);
96
+
97
+ let result = null;
98
+ try {
99
+ const ids = channelIds ?? resolveChannelIds(domain, eventType);
100
+ result = await send(event, ids);
101
+
102
+ if (!result?.ok) {
103
+ held.release();
104
+ return {
105
+ sent: false,
106
+ reason: `delivery failed on every channel (${result?.failed?.length ?? 0} error(s)); will retry`,
107
+ decision,
108
+ event,
109
+ send: result,
110
+ claimed: true,
111
+ };
112
+ }
113
+
114
+ // Order: record, emit, then drop the claim.
115
+ commitNotification(domain, eventType, decision);
116
+ if (emitLocal) {
117
+ try {
118
+ emitLocal(event);
119
+ } catch (err) {
120
+ // A broken socket must not undo a successful send.
121
+ console.error('[dispatch] local emit failed:', err.message);
122
+ }
123
+ }
124
+ held.commit();
125
+
126
+ return { sent: true, reason: decision.reason, decision, event, send: result, claimed: true };
127
+ } catch (err) {
128
+ // sendNotification() is not supposed to throw, but an injected sender or a
129
+ // module-load failure can. Release so it is retried rather than lost.
130
+ held.release();
131
+ return {
132
+ sent: false,
133
+ reason: `send threw: ${err.message}; will retry`,
134
+ decision,
135
+ event,
136
+ send: result,
137
+ claimed: true,
138
+ };
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Which channels a given event goes to.
144
+ *
145
+ * Global events (no domain) fan out to every channel configured for that event
146
+ * type; a domain event uses that domain's effective channels.
147
+ *
148
+ * @param {string|null} domain
149
+ * @param {string} eventType
150
+ * @returns {string[]}
151
+ */
152
+ export function resolveChannelIds(domain, eventType) {
153
+ return domain ? getEffectiveChannelIds(domain, eventType) : getAllDomainChannelIds(eventType);
154
+ }
@@ -38,23 +38,45 @@ export function getChannelById(id) {
38
38
  return loadChannels().find((ch) => ch.id === id) ?? null;
39
39
  }
40
40
 
41
+ /**
42
+ * What one sendNotification() call managed to do.
43
+ *
44
+ * @typedef {Object} SendResult
45
+ * @property {number} attempted Channels that existed and were tried
46
+ * @property {number} delivered Channels that accepted it
47
+ * @property {Array<{id: string, name: string, error: string}>} failed
48
+ * @property {boolean} ok True when it is safe to record this as sent
49
+ */
50
+
41
51
  /**
42
52
  * Send a notification to a specific set of channels identified by ID.
43
53
  * Each channel's send() is called in a try/catch — one failure won't block others.
44
54
  * Passing null or an empty array is a no-op (dashboard-only path).
45
55
  *
56
+ * Still never throws, but now REPORTS what happened. The caller needs this: a
57
+ * notification that reached no channel must not be recorded as sent, or it is
58
+ * never retried. Callers that ignore the return value behave exactly as before.
59
+ *
46
60
  * @param {Object} event - Notification event (type, message, severity, domain, timestamp)
47
61
  * @param {string[]|null} channelIds - Array of channel IDs to dispatch to
62
+ * @returns {Promise<SendResult>}
48
63
  */
49
64
  export async function sendNotification(event, channelIds = null) {
50
- if (!channelIds || channelIds.length === 0) return;
65
+ /** @type {SendResult} */
66
+ const result = { attempted: 0, delivered: 0, failed: [], ok: true };
67
+
68
+ if (!channelIds || channelIds.length === 0) return result;
51
69
 
52
70
  const channels = loadChannels();
53
71
 
54
72
  for (const id of channelIds) {
55
73
  const channel = channels.find((ch) => ch.id === id);
74
+ // An ID with no channel behind it is a stale reference, not a delivery
75
+ // failure: there is nothing to retry, so it is not counted as attempted.
56
76
  if (!channel) continue;
57
77
 
78
+ result.attempted++;
79
+
58
80
  try {
59
81
  const mod = await import(
60
82
  new URL(`./channels/${channel.type}.js`, import.meta.url)
@@ -62,12 +84,20 @@ export async function sendNotification(event, channelIds = null) {
62
84
 
63
85
  if (typeof mod.send !== 'function') {
64
86
  console.error(`[notifier] channel type "${channel.type}" missing send()`);
87
+ result.failed.push({ id, name: channel.name, error: `channel type "${channel.type}" has no send()` });
65
88
  continue;
66
89
  }
67
90
 
68
91
  await mod.send(event, channel);
92
+ result.delivered++;
69
93
  } catch (err) {
70
94
  console.error(`[notifier] channel "${channel.name}" (${channel.type}):`, err.message);
95
+ result.failed.push({ id, name: channel.name, error: err.message });
71
96
  }
72
97
  }
98
+
99
+ // Partial delivery counts as ok: re-sending would duplicate the notification
100
+ // on the channels that did work, which is worse than one channel missing it.
101
+ result.ok = result.attempted === 0 || result.delivered > 0;
102
+ return result;
73
103
  }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * core/passwords.js
3
+ *
4
+ * Password hashing for the dashboard login, built on node:crypto only — the
5
+ * constitution forbids adding a dependency, and scrypt is in the standard
6
+ * library precisely for this.
7
+ *
8
+ * Stored form:
9
+ *
10
+ * scrypt$<N>$<r>$<p>$<salt base64>$<key base64>
11
+ *
12
+ * The parameters travel with the hash so that raising them later does not
13
+ * invalidate existing passwords: verification reads the cost from the stored
14
+ * string, and needsRehash() reports when a stored hash is below the current
15
+ * defaults so the caller can upgrade it on the next successful login.
16
+ *
17
+ * Every comparison goes through timingSafeEqual. A plain `===` on secrets
18
+ * leaks their contents through how long it takes to fail.
19
+ */
20
+
21
+ import {
22
+ randomBytes,
23
+ scrypt as scryptCb,
24
+ timingSafeEqual,
25
+ createHash,
26
+ } from 'node:crypto';
27
+ import { promisify } from 'node:util';
28
+
29
+ const scrypt = promisify(scryptCb);
30
+
31
+ /** Current cost parameters. N=16384 needs 128*N*r = 16 MB of memory. */
32
+ const PARAMS = Object.freeze({ N: 16_384, r: 8, p: 1 });
33
+ const KEY_LEN = 64;
34
+ const SALT_LEN = 16;
35
+ const PREFIX = 'scrypt';
36
+
37
+ /** scrypt needs its memory limit raised to match N and r. */
38
+ const MAX_MEM = 64 * 1024 * 1024;
39
+
40
+ /**
41
+ * Minimum length for a new dashboard password.
42
+ *
43
+ * The single source of truth. Everything that enforces, displays or documents
44
+ * the minimum reads it from here — the API publishes it as
45
+ * `minPasswordLength` on GET /api/auth, and the UI uses that value rather than
46
+ * a literal of its own, so this number only has to change in one place.
47
+ */
48
+ export const MIN_PASSWORD_LENGTH = 6;
49
+
50
+ /**
51
+ * True when `stored` is one of our scrypt strings rather than a legacy
52
+ * plain-text password.
53
+ * @param {unknown} stored
54
+ * @returns {boolean}
55
+ */
56
+ export function isHashed(stored) {
57
+ return typeof stored === 'string' && stored.startsWith(`${PREFIX}$`);
58
+ }
59
+
60
+ /**
61
+ * Hashes a password with a fresh random salt.
62
+ * @param {string} password
63
+ * @returns {Promise<string>} The stored form
64
+ */
65
+ export async function hashPassword(password) {
66
+ if (typeof password !== 'string' || password.length === 0) {
67
+ throw new Error('A password is required');
68
+ }
69
+
70
+ const salt = randomBytes(SALT_LEN);
71
+ const key = await scrypt(password, salt, KEY_LEN, { ...PARAMS, maxmem: MAX_MEM });
72
+
73
+ return [
74
+ PREFIX,
75
+ PARAMS.N,
76
+ PARAMS.r,
77
+ PARAMS.p,
78
+ salt.toString('base64'),
79
+ key.toString('base64'),
80
+ ].join('$');
81
+ }
82
+
83
+ /**
84
+ * Verifies a password against a stored value.
85
+ *
86
+ * Accepts both the scrypt form and a legacy plain-text password, so an
87
+ * existing installation keeps working until the next successful login
88
+ * migrates it — see needsMigration().
89
+ *
90
+ * Never throws: a malformed stored value is a failed login, not a crash that
91
+ * could take the dashboard down.
92
+ *
93
+ * @param {string} password
94
+ * @param {string} stored
95
+ * @returns {Promise<boolean>}
96
+ */
97
+ export async function verifyPassword(password, stored) {
98
+ if (typeof password !== 'string' || typeof stored !== 'string') return false;
99
+ if (password.length === 0 || stored.length === 0) return false;
100
+
101
+ if (!isHashed(stored)) {
102
+ // Legacy plain text. Compared through fixed-width digests so the
103
+ // comparison stays constant-time even though the two strings may differ
104
+ // in length — timingSafeEqual throws on a length mismatch.
105
+ return timingSafeEqual(sha256(password), sha256(stored));
106
+ }
107
+
108
+ const parts = stored.split('$');
109
+ if (parts.length !== 6) return false;
110
+
111
+ const [, nRaw, rRaw, pRaw, saltB64, keyB64] = parts;
112
+ const N = Number(nRaw);
113
+ const r = Number(rRaw);
114
+ const p = Number(pRaw);
115
+ if (!Number.isInteger(N) || !Number.isInteger(r) || !Number.isInteger(p)) return false;
116
+
117
+ let expected;
118
+ let salt;
119
+ try {
120
+ salt = Buffer.from(saltB64, 'base64');
121
+ expected = Buffer.from(keyB64, 'base64');
122
+ } catch {
123
+ return false;
124
+ }
125
+ if (salt.length === 0 || expected.length === 0) return false;
126
+
127
+ let actual;
128
+ try {
129
+ actual = await scrypt(password, salt, expected.length, { N, r, p, maxmem: MAX_MEM });
130
+ } catch {
131
+ // Absurd stored parameters (a corrupted record, or one written by
132
+ // something else) must fail the login rather than throw.
133
+ return false;
134
+ }
135
+
136
+ return timingSafeEqual(actual, expected);
137
+ }
138
+
139
+ /**
140
+ * True when a stored value should be replaced by a fresh hash after a
141
+ * successful login: either it is still plain text, or it was hashed with
142
+ * weaker parameters than we now use.
143
+ *
144
+ * @param {string} stored
145
+ * @returns {boolean}
146
+ */
147
+ export function needsMigration(stored) {
148
+ if (typeof stored !== 'string' || stored.length === 0) return false;
149
+ if (!isHashed(stored)) return true;
150
+
151
+ const [, nRaw, rRaw, pRaw] = stored.split('$');
152
+ return Number(nRaw) < PARAMS.N || Number(rRaw) < PARAMS.r || Number(pRaw) < PARAMS.p;
153
+ }
154
+
155
+ /**
156
+ * Validates a password a user is trying to set.
157
+ * @param {unknown} password
158
+ * @returns {string|null} An error message, or null when acceptable
159
+ */
160
+ export function validateNewPassword(password) {
161
+ if (typeof password !== 'string' || password.length === 0) {
162
+ return 'A password is required.';
163
+ }
164
+ if (password.length < MIN_PASSWORD_LENGTH) {
165
+ return `The password must be at least ${MIN_PASSWORD_LENGTH} characters.`;
166
+ }
167
+ return null;
168
+ }
169
+
170
+ function sha256(value) {
171
+ return createHash('sha256').update(String(value), 'utf8').digest();
172
+ }
@@ -43,21 +43,25 @@ export async function setupLinuxPermissions() {
43
43
  await runInteractive(`sudo chown -R ${user}:${user} /etc/nginx/conf.d 2>/dev/null || true`);
44
44
 
45
45
  // Step 4: write sudoers file
46
+ // Exactly the commands Easy DevOps runs, and nothing more.
47
+ //
48
+ // A bare '/usr/bin/systemctl' used to be granted here, which allowed every
49
+ // systemctl verb against every unit — far beyond what this tool needs, and
50
+ // enough to disable or mask unrelated services. certbot is also gone: SSL is
51
+ // issued in-process with acme-client and no binary is ever invoked.
46
52
  const SUDO_RULES = [
47
53
  '/usr/bin/systemctl start nginx',
48
54
  '/usr/bin/systemctl stop nginx',
49
55
  '/usr/bin/systemctl reload nginx',
50
56
  '/usr/bin/systemctl restart nginx',
51
- '/usr/bin/systemctl',
57
+ '/usr/bin/systemctl is-active nginx',
58
+ '/usr/bin/systemctl status nginx',
52
59
  `${nginxPath}`,
53
60
  `${nginxPath} -t`,
54
61
  `${nginxPath} -s reload`,
55
62
  `${nginxPath} -s stop`,
56
63
  `${nginxPath} -s quit`,
57
- '/usr/bin/certbot',
58
64
  '/usr/bin/mkdir',
59
- '/usr/bin/cp',
60
- '/usr/bin/chmod',
61
65
  '/usr/bin/chown',
62
66
  '/usr/bin/tee',
63
67
  ].join(', ');