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.
Files changed (132) 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 +17 -5
  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 +93 -2
  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/channels/discord.js +77 -0
  42. package/src/core/channels/telegram.js +120 -0
  43. package/src/core/cleanup.js +600 -0
  44. package/src/core/config.js +169 -2
  45. package/src/core/daemon/ipc.js +292 -0
  46. package/src/core/daemon/lock.js +294 -0
  47. package/src/core/daemon/run.js +241 -0
  48. package/src/core/daemon/stopRequest.js +162 -0
  49. package/src/core/db.js +44 -8
  50. package/src/core/deploy/apps.js +491 -0
  51. package/src/core/deploy/domainLink.js +200 -0
  52. package/src/core/deploy/engine.js +973 -0
  53. package/src/core/deploy/ezfile.js +361 -0
  54. package/src/core/deploy/github.js +239 -0
  55. package/src/core/deploy/githubApi.js +261 -0
  56. package/src/core/deploy/hookServer.js +325 -0
  57. package/src/core/deploy/hubCommands.js +267 -0
  58. package/src/core/deploy/launcher.js +57 -0
  59. package/src/core/deploy/status.js +91 -0
  60. package/src/core/deploy/store.js +398 -0
  61. package/src/core/domainNotifier.js +364 -0
  62. package/src/core/domains-db.js +234 -0
  63. package/src/core/events.js +222 -0
  64. package/src/core/hub/agent.js +842 -0
  65. package/src/core/hubLink.js +306 -0
  66. package/src/core/hubPermissions.js +430 -0
  67. package/src/core/installSource.js +162 -0
  68. package/src/core/jobs/bus.js +120 -0
  69. package/src/core/jobs/index.js +371 -0
  70. package/src/core/jobs/monitors.js +368 -0
  71. package/src/core/jobs/owner.js +217 -0
  72. package/src/core/jobs/revisionWatcher.js +106 -0
  73. package/src/core/nginx-apply.js +213 -0
  74. package/src/core/nginx-conf-generator.js +253 -17
  75. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  76. package/src/core/notifications/claim.js +214 -0
  77. package/src/core/notifications/dispatch.js +154 -0
  78. package/src/core/notifier.js +103 -0
  79. package/src/core/passwords.js +172 -0
  80. package/src/core/permissions.js +8 -4
  81. package/src/core/platform.js +709 -2
  82. package/src/core/probeCache.js +258 -0
  83. package/src/core/purge.js +372 -0
  84. package/src/core/runner.js +488 -0
  85. package/src/core/service/acl.js +226 -0
  86. package/src/core/service/dataDir.js +345 -0
  87. package/src/core/service/index.js +1128 -0
  88. package/src/core/service/legacy.js +218 -0
  89. package/src/core/service/runtime.js +446 -0
  90. package/src/core/service/runtimeUpdate.js +800 -0
  91. package/src/core/service/systemd.js +458 -0
  92. package/src/core/service/windowsPersonal.js +530 -0
  93. package/src/core/service/windowsService.js +576 -0
  94. package/src/core/service/winsw.js +260 -0
  95. package/src/core/setupCode.js +331 -0
  96. package/src/core/shell.js +128 -13
  97. package/src/core/ssl-issuer.js +627 -0
  98. package/src/core/updater.js +295 -0
  99. package/src/core/validators.js +99 -0
  100. package/src/dashboard/controllers/authController.js +316 -0
  101. package/src/dashboard/controllers/deploymentsController.js +479 -0
  102. package/src/dashboard/controllers/domainsController.js +403 -0
  103. package/src/dashboard/controllers/hubController.js +135 -0
  104. package/src/dashboard/controllers/nginxController.js +146 -0
  105. package/src/dashboard/controllers/processesController.js +368 -0
  106. package/src/dashboard/controllers/settingsController.js +503 -0
  107. package/src/dashboard/controllers/sslController.js +452 -0
  108. package/src/dashboard/lib/daemonBridge.js +163 -0
  109. package/src/dashboard/lib/localRequest.js +235 -0
  110. package/src/dashboard/lib/loginRateLimit.js +119 -0
  111. package/src/dashboard/lib/requireAuth.js +80 -0
  112. package/src/dashboard/public/img/icon.png +0 -0
  113. package/src/dashboard/public/img/icon_b.png +0 -0
  114. package/src/dashboard/public/js/app.js +595 -19
  115. package/src/dashboard/routes/auth.js +14 -33
  116. package/src/dashboard/routes/deployments.js +46 -0
  117. package/src/dashboard/routes/domains.js +20 -363
  118. package/src/dashboard/routes/hub.js +22 -0
  119. package/src/dashboard/routes/nginx.js +22 -146
  120. package/src/dashboard/routes/processes.js +29 -0
  121. package/src/dashboard/routes/settings.js +25 -232
  122. package/src/dashboard/routes/ssl.js +18 -276
  123. package/src/dashboard/server.js +279 -165
  124. package/src/dashboard/socketManager.js +246 -0
  125. package/src/dashboard/views/index.ejs +1 -0
  126. package/src/dashboard/views/partials/domain-form.ejs +64 -1
  127. package/src/dashboard/views/partials/login.ejs +69 -8
  128. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  129. package/src/dashboard/views/partials/settings-panel.ejs +549 -118
  130. package/src/dashboard/views/partials/sidebar.ejs +3 -1
  131. package/src/dashboard/lib/domains-db.js +0 -51
  132. /package/src/{dashboard/routes → core/channels}/.gitkeep +0 -0
@@ -1,57 +1,43 @@
1
1
  /**
2
2
  * cli/menus/update.js
3
3
  *
4
- * Check for updates and upgrade easy-devops in place.
4
+ * `ezz update`, and the same operation from the interactive menu.
5
5
  *
6
- * Flow:
7
- * 1. Fetch latest version from npm registry
8
- * 2. If an update is available, offer to install it
9
- * 3. Before installing: record dashboard running state in DB
10
- * (key: 'update-pre-dashboard') so it survives a crash mid-update
11
- * 4. Stop dashboard if it was running
12
- * 5. Run: npm install -g easy-devops@<latest>
13
- * 6. Re-start dashboard if it was running before
14
- * 7. Clear the saved state key
6
+ * The sequence lives in core/updater.js: establish how this copy was installed
7
+ * (npm or a git clone), stop the background service, replace the package,
8
+ * refresh the Windows Server runtime copy, start, verify against the daemon's
9
+ * own heartbeat, and roll back if the new version does not come up.
10
+ *
11
+ * This file owns only what is genuinely CLI: the questions, the output, and the
12
+ * detached dashboard (cli/menus/dashboard.js), plus the `update-pre-dashboard`
13
+ * key that lets a crash mid-update still bring the dashboard back on the next
14
+ * launch.
15
+ *
16
+ * Nothing here runs from the dashboard or the Hub, and `whyCliOnly()` in
17
+ * core/updater.js is what explains that to the user rather than a comment.
15
18
  */
16
19
 
17
20
  import chalk from 'chalk';
18
21
  import inquirer from 'inquirer';
19
22
  import ora from 'ora';
20
- import path from 'path';
21
- import { fileURLToPath } from 'url';
22
- import { createRequire } from 'module';
23
- import { run } from '../../core/shell.js';
24
- import { dbGet, dbSet, closeDb, initDb } from '../../core/db.js';
23
+ import { dbGet, dbSet } from '../../core/db.js';
25
24
  import { loadConfig } from '../../core/config.js';
26
25
  import { getDashboardStatus, startDashboard, stopDashboard } from './dashboard.js';
27
26
 
28
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
- const require = createRequire(import.meta.url);
30
- const { version: currentVersion } = require('../../../package.json');
31
-
32
- // ─── Version helpers ──────────────────────────────────────────────────────────
33
-
34
- async function fetchLatestVersion() {
35
- const result = await run('npm view easy-devops version', { timeout: 20000 });
36
- if (result.success && result.stdout.trim()) return result.stdout.trim();
37
- return null;
38
- }
39
-
40
- function isNewer(latest, current) {
41
- const parse = v => v.replace(/^v/, '').split('.').map(Number);
42
- const [la, lb, lc] = parse(latest);
43
- const [ca, cb, cc] = parse(current);
44
- if (la !== ca) return la > ca;
45
- if (lb !== cb) return lb > cb;
46
- return lc > cc;
47
- }
48
-
49
27
  // ─── Recover interrupted update ───────────────────────────────────────────────
50
28
  // If a previous update crashed after stopping the dashboard but before restarting
51
29
  // it, the key 'update-pre-dashboard' is still set. Offer to restart it.
52
30
 
53
31
  async function recoverIfNeeded() {
54
32
  const saved = dbGet('update-pre-dashboard');
33
+
34
+ // A service-managed dashboard needs no recovery prompt: PM2 brought it back
35
+ // on its own, or `ezz service restart` will.
36
+ if (saved?.service) {
37
+ dbSet('update-pre-dashboard', null);
38
+ return;
39
+ }
40
+
55
41
  if (!saved?.wasRunning) return;
56
42
 
57
43
  console.log(chalk.yellow('\n A previous update left the dashboard stopped.'));
@@ -76,55 +62,225 @@ async function recoverIfNeeded() {
76
62
 
77
63
  // ─── Perform update ───────────────────────────────────────────────────────────
78
64
 
65
+ /**
66
+ * The menu's update, which is the same operation `ezz update` performs.
67
+ *
68
+ * The sequence itself — stop the service, replace the package, refresh the
69
+ * Windows Server runtime copy, start, verify against the daemon's own
70
+ * heartbeat, roll back if it did not come up — lives in core/updater.js.
71
+ * Having had two copies of it was how the runtime copy came to be refreshed in
72
+ * neither: a feature added to one path is invisible to the other.
73
+ *
74
+ * What stays here is the detached dashboard, which is a CLI concept, and the
75
+ * recovery key that survives a crash mid-update.
76
+ */
79
77
  async function performUpdate(latestVersion) {
80
- // Step 1 — snapshot dashboard state and persist it
78
+ const updater = await import('../../core/updater.js');
79
+ const { detectInstallSource, describeUnmanaged } = await import('../../core/installSource.js');
80
+
81
+ const source = detectInstallSource();
82
+ if (!source.npmUpdatable) {
83
+ console.log();
84
+ for (const line of describeUnmanaged(source, 'update')) console.log(' ' + chalk.gray(line));
85
+ return false;
86
+ }
87
+
88
+ for (const line of updater.whyCliOnly()) console.log(' ' + chalk.gray(line));
89
+ console.log();
90
+
91
+ // Step 1 — the dashboard's state, persisted so a crash mid-update can still
92
+ // bring it back on the next launch (recoverIfNeeded above).
81
93
  const status = await getDashboardStatus();
82
94
  dbSet('update-pre-dashboard', {
83
95
  wasRunning: status.running,
84
- pid: status.pid,
85
- port: status.port,
96
+ pid: status.pid,
97
+ port: status.port,
98
+ service: false,
86
99
  });
87
100
 
88
- // Step 2 — stop dashboard if running
89
101
  if (status.running) {
90
102
  const sp = ora('Stopping dashboard...').start();
91
103
  await stopDashboard(status.pid);
92
104
  sp.succeed('Dashboard stopped');
93
105
  }
94
106
 
95
- // Step 3 — close the SQLite connection so npm can rename the db file (EBUSY on Windows)
96
- closeDb();
107
+ // Step 2 — the package and the service.
108
+ const result = await updater.performUpdate({
109
+ version: latestVersion,
110
+ log: (line) => console.log(' ' + chalk.gray(line)),
111
+ });
97
112
 
98
- // Step 4 — install new version
99
- const sp = ora(`Installing easy-devops@${latestVersion}...`).start();
100
- const result = await run(`npm install -g easy-devops@${latestVersion}`, { timeout: 120000 });
113
+ // Step 3 — the dashboard, however it was before.
114
+ const saved = dbGet('update-pre-dashboard');
115
+ dbSet('update-pre-dashboard', null);
101
116
 
102
- if (!result.success) {
103
- sp.fail('Update failed');
104
- console.log(chalk.red('\n' + (result.stderr || result.stdout) + '\n'));
105
- // Leave 'update-pre-dashboard' in DB so recovery runs on next launch
106
- return false;
117
+ if (saved?.wasRunning) {
118
+ const port = saved.port || loadConfig().dashboardPort;
119
+ const sp = ora(`Restarting dashboard on port ${port}...`).start();
120
+ const back = await startDashboard(port);
121
+ back.success
122
+ ? sp.succeed(`Dashboard restarted on port ${port}`)
123
+ : sp.fail('Could not restart dashboard — use the Dashboard menu');
107
124
  }
108
125
 
109
- sp.succeed(`Updated to v${latestVersion}`);
126
+ if (result.ok) {
127
+ console.log(' ' + chalk.green(`Updated to v${result.to}`));
128
+ if (result.serviceInstalled && result.runningVersion) {
129
+ console.log(' ' + chalk.gray(`The service reports v${result.runningVersion}.`));
130
+ }
131
+ return true;
132
+ }
110
133
 
111
- // Re-initialize the database connection after npm replaced the module
112
- initDb();
134
+ console.log(' ' + chalk.red(`Update failed (${result.step})`));
135
+ for (const line of String(result.reason ?? '').split('\n')) console.log(' ' + chalk.gray(line));
136
+ if (result.rolledBack) {
137
+ console.log(' ' + chalk.green(`Rolled back to v${result.from}.`));
138
+ }
139
+ return false;
140
+ }
113
141
 
114
- // Step 5 — restart dashboard if it was running before
115
- const saved = dbGet('update-pre-dashboard');
116
- dbSet('update-pre-dashboard', null);
142
+ // ─── `ezz update` ─────────────────────────────────────────────────────────────
117
143
 
118
- if (saved?.wasRunning) {
119
- const port = saved.port || loadConfig().dashboardPort;
120
- const restSp = ora(`Restarting dashboard on port ${port}...`).start();
121
- const res = await startDashboard(port);
122
- res.success
123
- ? restSp.succeed(`Dashboard restarted on port ${port}`)
124
- : restSp.fail('Could not restart dashboard — use the Dashboard menu');
144
+ /**
145
+ * Non-interactive update.
146
+ *
147
+ * Shares `core/updater.js` with the menu above, so there is one implementation
148
+ * of "stop, replace, refresh the copy, start, verify, roll back" and the two
149
+ * entry points cannot drift. What stays here is the part that is genuinely
150
+ * CLI-only: a detached dashboard, which cli/menus/dashboard.js owns.
151
+ *
152
+ * @param {Object} [opts]
153
+ * @param {boolean} [opts.yes] Skip the confirmation
154
+ * @returns {Promise<number>} Process exit code
155
+ */
156
+ export async function updateCommand({ yes = false } = {}) {
157
+ const updater = await import('../../core/updater.js');
158
+
159
+ console.log();
160
+ console.log(' ' + chalk.bold('Update Easy DevOps'));
161
+ console.log(' ' + chalk.gray('-'.repeat(58)));
162
+ console.log();
163
+
164
+ const spinner = ora('Checking the registry...').start();
165
+ const check = await updater.checkForUpdate();
166
+ spinner.stop();
167
+
168
+ console.log(` Installed : ${chalk.cyan('v' + check.current)}`);
169
+
170
+ if (!check.reachable) {
171
+ console.log(' ' + chalk.yellow('Could not reach the npm registry.'));
172
+ console.log(' ' + chalk.gray('Check your internet connection and try again.'));
173
+ console.log();
174
+ return 1;
175
+ }
176
+
177
+ console.log(` Latest : ${chalk.green('v' + check.latest)}`);
178
+ console.log();
179
+
180
+ // The install source is checked before anything is offered: on a clone the
181
+ // answer is `git pull`, and asking "update to v1.3.0?" first would be
182
+ // offering something that cannot happen.
183
+ const { detectInstallSource, describeUnmanaged } = await import('../../core/installSource.js');
184
+ const source = detectInstallSource();
185
+
186
+ if (!source.npmUpdatable) {
187
+ for (const line of describeUnmanaged(source, 'update')) console.log(' ' + chalk.gray(line));
188
+ if (check.updateAvailable) {
189
+ console.log(' ' + chalk.gray(`The registry has v${check.latest}; this clone is at v${check.current}.`));
190
+ console.log();
191
+ }
192
+ return 1;
193
+ }
194
+
195
+ if (!check.updateAvailable) {
196
+ console.log(' ' + chalk.green('Already up to date.'));
197
+ console.log();
198
+ return 0;
199
+ }
200
+
201
+ for (const line of updater.whyCliOnly()) console.log(' ' + chalk.gray(line));
202
+ console.log();
203
+
204
+ if (!yes) {
205
+ let confirm = false;
206
+ try {
207
+ ({ confirm } = await inquirer.prompt([{
208
+ type: 'confirm',
209
+ name: 'confirm',
210
+ message: `Update to v${check.latest}? The background service will be restarted.`,
211
+ default: true,
212
+ }]));
213
+ } catch (err) {
214
+ if (err.name === 'ExitPromptError') return 2;
215
+ throw err;
216
+ }
217
+ if (!confirm) {
218
+ console.log(' ' + chalk.gray('Nothing was changed.'));
219
+ return 0;
220
+ }
221
+ }
222
+
223
+ // A detached dashboard runs the jobs while no service does, and it is
224
+ // running the code npm is about to replace. Stopped here and started again
225
+ // afterwards, which is exactly what the menu path does.
226
+ const dash = await getDashboardStatus();
227
+ if (dash.running) {
228
+ const sp = ora('Stopping the dashboard...').start();
229
+ await stopDashboard(dash.pid);
230
+ sp.succeed('Dashboard stopped');
231
+ }
232
+
233
+ console.log();
234
+ const result = await updater.performUpdate({
235
+ version: check.latest,
236
+ log: (line) => console.log(' ' + chalk.gray(line)),
237
+ });
238
+ console.log();
239
+
240
+ if (dash.running) {
241
+ const port = dash.port || loadConfig().dashboardPort;
242
+ const sp = ora(`Starting the dashboard on port ${port}...`).start();
243
+ const back = await startDashboard(port);
244
+ back.success
245
+ ? sp.succeed(`Dashboard running on port ${port}`)
246
+ : sp.fail('Could not start the dashboard - use the Dashboard menu');
247
+ }
248
+
249
+ if (result.ok) {
250
+ console.log(' ' + chalk.green(`Updated v${result.from} -> v${result.to}.`));
251
+ if (result.serviceInstalled) {
252
+ console.log(' ' + chalk.gray(
253
+ result.versionConfirmed
254
+ ? `The service is running v${result.runningVersion} (reported by the daemon itself).`
255
+ : `The service restarted, reporting v${result.runningVersion ?? 'an unknown version'}.`,
256
+ ));
257
+ if (result.refreshedCopy) {
258
+ console.log(' ' + chalk.gray('The ProgramData runtime copy was refreshed, so the service runs the new code.'));
259
+ }
260
+ }
261
+ console.log();
262
+ return 0;
263
+ }
264
+
265
+ console.log(' ' + chalk.red(`The update failed (${result.step}).`));
266
+ console.log();
267
+ for (const line of String(result.reason ?? '').split('\n')) console.log(' ' + line);
268
+ console.log();
269
+
270
+ if (result.untouched) {
271
+ console.log(' ' + chalk.green('Nothing was changed.'));
272
+ } else if (result.rolledBack) {
273
+ console.log(' ' + chalk.green(`Rolled back to v${result.from}.`)
274
+ + (result.restored ? chalk.gray(' The service is running again.') : ''));
275
+ if (!result.restored) {
276
+ console.log(' ' + chalk.yellow('The service did not come back: ') + chalk.white('ezz service start'));
277
+ }
278
+ } else if (result.restarted) {
279
+ console.log(' ' + chalk.gray('The service was started again on the version it had.'));
125
280
  }
126
281
 
127
- return true;
282
+ console.log();
283
+ return 1;
128
284
  }
129
285
 
130
286
  // ─── Menu ─────────────────────────────────────────────────────────────────────
@@ -147,7 +303,7 @@ export default async function updateMenu() {
147
303
  return;
148
304
  }
149
305
 
150
- const updateAvailable = isNewer(latestVersion, currentVersion);
306
+ const updateAvailable = check.updateAvailable;
151
307
 
152
308
  if (updateAvailable) {
153
309
  console.log(` Latest version : ${chalk.green('v' + latestVersion)} ${chalk.yellow('← update available')}\n`);
@@ -0,0 +1,273 @@
1
+ /**
2
+ * core/acme-challenge.js
3
+ *
4
+ * The temporary HTTP listener that answers ACME HTTP-01 challenges, plus the
5
+ * local preflight that proves nginx can reach it before Let's Encrypt is
6
+ * contacted.
7
+ *
8
+ * Why a loopback listener behind nginx rather than a webroot: on Linux nginx
9
+ * runs as another user and cannot read files under the operator's config
10
+ * directory, and creating a system webroot would need extra sudo rules. A
11
+ * proxy_pass to 127.0.0.1 behaves identically on Linux and Windows and needs
12
+ * no filesystem permissions at all.
13
+ *
14
+ * Concurrency: the listener is reference counted and every start/stop goes
15
+ * through one promise chain, so two issuances running at once share a single
16
+ * listener and the last one out closes it.
17
+ */
18
+
19
+ import http from 'http';
20
+ import net from 'net';
21
+ import { ACME_CHALLENGE_PATH, DEFAULT_ACME_CHALLENGE_PORT } from './nginx-conf-generator.js';
22
+
23
+ /** token -> keyAuthorization, shared by every concurrent issuance. */
24
+ const tokens = new Map();
25
+
26
+ let server = null;
27
+ let serverPort = null;
28
+ let refCount = 0;
29
+
30
+ /** Serialises start/stop so concurrent callers cannot race the listener. */
31
+ let chain = Promise.resolve();
32
+
33
+ /** Runs `fn` with exclusive access to the listener bookkeeping. */
34
+ function serialize(fn) {
35
+ const next = chain.then(fn, fn);
36
+ // Keep the chain alive regardless of outcome.
37
+ chain = next.then(() => undefined, () => undefined);
38
+ return next;
39
+ }
40
+
41
+ /** True when something is already listening on the port. */
42
+ export function isPortBusy(port, host = '127.0.0.1') {
43
+ return new Promise((resolve) => {
44
+ const probe = net.connect({ port, host });
45
+ const done = (busy) => {
46
+ probe.removeAllListeners();
47
+ probe.destroy();
48
+ resolve(busy);
49
+ };
50
+ probe.once('connect', () => done(true));
51
+ probe.once('error', () => done(false));
52
+ setTimeout(() => done(false), 1500);
53
+ });
54
+ }
55
+
56
+ function createServer() {
57
+ return http.createServer((req, res) => {
58
+ let pathname = req.url || '/';
59
+ const q = pathname.indexOf('?');
60
+ if (q !== -1) pathname = pathname.slice(0, q);
61
+
62
+ if (pathname.startsWith(ACME_CHALLENGE_PATH)) {
63
+ const token = pathname.slice(ACME_CHALLENGE_PATH.length);
64
+ const keyAuth = tokens.get(token);
65
+ if (keyAuth) {
66
+ res.writeHead(200, {
67
+ 'Content-Type': 'application/octet-stream',
68
+ 'Content-Length': Buffer.byteLength(keyAuth),
69
+ });
70
+ res.end(keyAuth);
71
+ return;
72
+ }
73
+ }
74
+
75
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
76
+ res.end('Not found');
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Starts the listener if it is not already running and increments the refcount.
82
+ * @param {number} port
83
+ * @returns {Promise<number>} The bound port
84
+ */
85
+ function acquire(port) {
86
+ return serialize(async () => {
87
+ if (server) {
88
+ if (serverPort !== port) {
89
+ throw new Error(
90
+ `ACME challenge listener is already running on port ${serverPort}; ` +
91
+ `cannot also bind ${port}. Finish the other issuance first.`
92
+ );
93
+ }
94
+ refCount++;
95
+ return serverPort;
96
+ }
97
+
98
+ if (await isPortBusy(port)) {
99
+ throw new Error(
100
+ `Port ${port} on 127.0.0.1 is already in use, so the ACME challenge ` +
101
+ `listener cannot start. Stop whatever is using it, or set a different ` +
102
+ `acmeChallengePort in Settings (it must match the port in the nginx configs).`
103
+ );
104
+ }
105
+
106
+ const srv = createServer();
107
+ await new Promise((resolve, reject) => {
108
+ srv.once('error', reject);
109
+ srv.listen(port, '127.0.0.1', () => {
110
+ srv.removeListener('error', reject);
111
+ resolve();
112
+ });
113
+ });
114
+
115
+ server = srv;
116
+ serverPort = port;
117
+ refCount = 1;
118
+ return serverPort;
119
+ });
120
+ }
121
+
122
+ /** Decrements the refcount and closes the listener when it hits zero. */
123
+ function release() {
124
+ return serialize(async () => {
125
+ refCount = Math.max(0, refCount - 1);
126
+ if (refCount > 0 || !server) return;
127
+
128
+ const srv = server;
129
+ server = null;
130
+ serverPort = null;
131
+
132
+ await new Promise((resolve) => {
133
+ const done = setTimeout(resolve, 2000);
134
+ srv.close(() => {
135
+ clearTimeout(done);
136
+ resolve();
137
+ });
138
+ });
139
+ });
140
+ }
141
+
142
+ /**
143
+ * Runs `fn` with the challenge listener available.
144
+ *
145
+ * @param {number} port Loopback port to serve on
146
+ * @param {(api: {
147
+ * port: number,
148
+ * setToken: (token: string, keyAuth: string) => void,
149
+ * removeToken: (token: string) => void,
150
+ * }) => Promise<any>} fn
151
+ * @returns {Promise<any>} Whatever `fn` resolves to
152
+ */
153
+ export async function withChallengeServer(port, fn) {
154
+ const bound = await acquire(port);
155
+ const owned = new Set();
156
+
157
+ try {
158
+ return await fn({
159
+ port: bound,
160
+ setToken(token, keyAuth) {
161
+ tokens.set(token, keyAuth);
162
+ owned.add(token);
163
+ },
164
+ removeToken(token) {
165
+ tokens.delete(token);
166
+ owned.delete(token);
167
+ },
168
+ });
169
+ } finally {
170
+ // Never leave this issuance's tokens behind for another one to serve.
171
+ for (const token of owned) tokens.delete(token);
172
+ await release();
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Fetches a URL with an explicit Host header and a short timeout.
178
+ * @returns {Promise<{ ok: boolean, status: number|null, body: string, error: string|null }>}
179
+ */
180
+ function probe({ host, port, path: reqPath, hostHeader, timeout = 5000 }) {
181
+ return new Promise((resolve) => {
182
+ const req = http.request(
183
+ { host, port, path: reqPath, method: 'GET', headers: { Host: hostHeader }, timeout },
184
+ (res) => {
185
+ let body = '';
186
+ res.setEncoding('utf8');
187
+ res.on('data', (c) => { body += c; });
188
+ res.on('end', () => resolve({ ok: true, status: res.statusCode, body, error: null }));
189
+ }
190
+ );
191
+ req.on('timeout', () => { req.destroy(); resolve({ ok: false, status: null, body: '', error: 'timed out' }); });
192
+ req.on('error', (err) => resolve({ ok: false, status: null, body: '', error: err.message }));
193
+ req.end();
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Chooses which address(es) to probe for a domain's port-80 server block.
199
+ *
200
+ * A config that binds a specific address (`listen 203.0.113.5:80`) is not
201
+ * reachable on 127.0.0.1, so probing loopback would wrongly look like a
202
+ * broken setup. Wildcard listens are reachable on loopback.
203
+ *
204
+ * @param {Array<{host: string, port: number, wildcard: boolean}>} listens
205
+ * @returns {string[]} Hosts to try, in order
206
+ */
207
+ export function resolveProbeHosts(listens) {
208
+ if (!Array.isArray(listens) || listens.length === 0) return ['127.0.0.1'];
209
+ if (listens.some((l) => l.wildcard)) return ['127.0.0.1'];
210
+
211
+ // Specific addresses only — probe each one as bound.
212
+ const hosts = [];
213
+ for (const l of listens) {
214
+ const host = l.host === '::1' ? '::1' : l.host;
215
+ if (!hosts.includes(host)) hosts.push(host);
216
+ }
217
+ return hosts;
218
+ }
219
+
220
+ /**
221
+ * Confirms nginx forwards the challenge path to our listener, by serving a
222
+ * throwaway token and fetching it back through nginx.
223
+ *
224
+ * Runs entirely on this machine: it never contacts Let's Encrypt, so a failure
225
+ * here costs nothing against the rate limits.
226
+ *
227
+ * @param {Object} opts
228
+ * @param {string} opts.domain Host header to send
229
+ * @param {number} opts.challengePort Loopback port of our listener
230
+ * @param {string[]} [opts.probeHosts] Addresses to try (from resolveProbeHosts)
231
+ * @param {number} [opts.httpPort] Port nginx serves HTTP on
232
+ * @returns {Promise<{ ok: boolean, detail: string, triedHosts: string[] }>}
233
+ */
234
+ export async function preflight({
235
+ domain,
236
+ challengePort = DEFAULT_ACME_CHALLENGE_PORT,
237
+ probeHosts = ['127.0.0.1'],
238
+ httpPort = 80,
239
+ }) {
240
+ const token = `easy-devops-preflight-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
241
+ const expected = `${token}.preflight`;
242
+ const attempts = [];
243
+
244
+ return withChallengeServer(challengePort, async ({ setToken }) => {
245
+ setToken(token, expected);
246
+
247
+ for (const host of probeHosts) {
248
+ const res = await probe({
249
+ host,
250
+ port: httpPort,
251
+ path: `${ACME_CHALLENGE_PATH}${token}`,
252
+ hostHeader: domain,
253
+ });
254
+
255
+ if (res.ok && res.status === 200 && res.body === expected) {
256
+ return { ok: true, detail: `${host}:${httpPort} returned the token`, triedHosts: probeHosts };
257
+ }
258
+
259
+ if (!res.ok) {
260
+ attempts.push(`${host}:${httpPort} — ${res.error}`);
261
+ } else if (res.status === 301 || res.status === 302) {
262
+ attempts.push(
263
+ `${host}:${httpPort} — HTTP ${res.status} redirect; the challenge path is being redirected ` +
264
+ `instead of proxied (the config may predate the ACME challenge location)`
265
+ );
266
+ } else {
267
+ attempts.push(`${host}:${httpPort} — HTTP ${res.status}, unexpected body`);
268
+ }
269
+ }
270
+
271
+ return { ok: false, detail: attempts.join('; ') || 'no addresses probed', triedHosts: probeHosts };
272
+ });
273
+ }