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
@@ -0,0 +1,479 @@
1
+ /**
2
+ * dashboard/controllers/deploymentsController.js
3
+ *
4
+ * The Deployments page: the app registry, starting and rolling back
5
+ * deployments, reading their logs, and the deploy hook's settings.
6
+ *
7
+ * A thin layer. Every rule lives in core/deploy/ — validation in apps.js, the
8
+ * pipeline in engine.js — so the Hub command path and the deploy hook reach
9
+ * exactly the same behaviour without going through HTTP.
10
+ *
11
+ * Two things this controller is careful about:
12
+ *
13
+ * 1. It never starts a PM2 daemon just to draw a list. Process status is
14
+ * read only when PM2's daemon is already running.
15
+ * 2. A deployment is started and answered with 202. The request does not
16
+ * wait for a build; the page polls the run.
17
+ */
18
+
19
+ import http from 'http';
20
+
21
+ import { loadConfig, saveConfig, BIND_ALL, BIND_LOOPBACK } from '../../core/config.js';
22
+ import { validatePort } from '../../core/validators.js';
23
+ import * as runner from '../../core/runner.js';
24
+ import { run as shellRun } from '../../core/shell.js';
25
+ import { getDomains, findDomain } from '../../core/domains-db.js';
26
+ import { writeConfWithTest } from '../../core/nginx-apply.js';
27
+ import { reloadNginx } from '../../core/ssl-issuer.js';
28
+ import { DEPLOY_HOOK_PATH } from '../../core/nginx-conf-generator.js';
29
+ import { loadChannels } from '../../core/notifier.js';
30
+
31
+ import {
32
+ getApp, createApp, updateApp, dashboardApp,
33
+ rotateHookToken, revokeHookToken, generateDeployKey,
34
+ DEFAULT_KEEP_RELEASES, MIN_KEEP_RELEASES, MAX_KEEP_RELEASES,
35
+ } from '../../core/deploy/apps.js';
36
+ import { startDeployment, startRollback, removeApp, moveApp } from '../../core/deploy/engine.js';
37
+ import { readRun, readLogTail, isId, deployRoot } from '../../core/deploy/store.js';
38
+ import { linkDomain, unlinkDomain } from '../../core/deploy/domainLink.js';
39
+ import { describeApps, describeAppDetail } from '../../core/deploy/status.js';
40
+ import { hookSettings } from '../../core/deploy/hookServer.js';
41
+ import { hookUrl } from '../../core/deploy/github.js';
42
+ import { githubSetupFor } from '../../core/deploy/hubCommands.js';
43
+ import { applyGithubSetup, parseGithubRepo, validateGithubToken } from '../../core/deploy/githubApi.js';
44
+ import { EZ_FILE_LOCATIONS } from '../../core/deploy/ezfile.js';
45
+
46
+ /** Asks the hook listener whether it is up. It may live in another process. */
47
+ function probeHook(port) {
48
+ return new Promise((resolve) => {
49
+ const req = http.request(
50
+ { host: '127.0.0.1', port, path: `${DEPLOY_HOOK_PATH}health`, method: 'GET', timeout: 1500 },
51
+ (res) => { res.resume(); resolve(res.statusCode === 200); },
52
+ );
53
+ req.on('timeout', () => { req.destroy(); resolve(false); });
54
+ req.on('error', () => resolve(false));
55
+ req.end();
56
+ });
57
+ }
58
+
59
+ async function hookStatus() {
60
+ const settings = hookSettings();
61
+ return {
62
+ ...settings,
63
+ listening: settings.enabled ? await probeHook(settings.port) : false,
64
+ path: DEPLOY_HOOK_PATH,
65
+ };
66
+ }
67
+
68
+ function errorBody(result) {
69
+ return { error: result.errors?.[0] ?? result.error ?? 'Request failed', errors: result.errors ?? undefined };
70
+ }
71
+
72
+ class DeploymentsController {
73
+ /** GET /api/deployments */
74
+ async list(req, res, next) {
75
+ try {
76
+ const [git, pm2] = await Promise.all([
77
+ shellRun('git --version', { timeout: 10000 }),
78
+ runner.detect({ probeVersion: false }),
79
+ ]);
80
+
81
+ res.json({
82
+ apps: await describeApps(),
83
+ hook: await hookStatus(),
84
+ requirements: {
85
+ git: git.success,
86
+ gitVersion: git.success ? git.stdout.replace(/^git version\s*/i, '').trim() : null,
87
+ pm2: pm2.installed,
88
+ },
89
+ limits: {
90
+ keepReleasesDefault: DEFAULT_KEEP_RELEASES,
91
+ keepReleasesMin: MIN_KEEP_RELEASES,
92
+ keepReleasesMax: MAX_KEEP_RELEASES,
93
+ },
94
+ ezFileLocations: EZ_FILE_LOCATIONS,
95
+ // Where a NEW app would be created. Existing apps report their own `dir`.
96
+ deployDir: deployRoot(),
97
+ // Offered in the form so a deployment's outcome can be sent somewhere.
98
+ channels: loadChannels().map((ch) => ({ id: ch.id, name: ch.name, type: ch.type })),
99
+ // Offered as the domain to expose the hook through.
100
+ domains: getDomains().map((d) => ({
101
+ name: d.name, enabled: d.enabled !== false, ssl: Boolean(d.ssl?.enabled),
102
+ })),
103
+ });
104
+ } catch (error) {
105
+ next(error);
106
+ }
107
+ }
108
+
109
+ /** POST /api/deployments */
110
+ create(req, res, next) {
111
+ try {
112
+ const result = createApp(req.body ?? {});
113
+ if (!result.ok) return res.status(result.status).json(errorBody(result));
114
+ return res.status(201).json(dashboardApp(result.app));
115
+ } catch (error) {
116
+ return next(error);
117
+ }
118
+ }
119
+
120
+ /** GET /api/deployments/:id */
121
+ async get(req, res, next) {
122
+ try {
123
+ const detail = await describeAppDetail(req.params.id);
124
+ if (!detail) return res.status(404).json({ error: `No app named "${req.params.id}".` });
125
+ return res.json(detail);
126
+ } catch (error) {
127
+ return next(error);
128
+ }
129
+ }
130
+
131
+ /** PUT /api/deployments/:id */
132
+ update(req, res, next) {
133
+ try {
134
+ const result = updateApp(req.params.id, req.body ?? {});
135
+ if (!result.ok) return res.status(result.status).json(errorBody(result));
136
+ return res.json(dashboardApp(result.app));
137
+ } catch (error) {
138
+ return next(error);
139
+ }
140
+ }
141
+
142
+ /** DELETE /api/deployments/:id */
143
+ async remove(req, res, next) {
144
+ try {
145
+ const deleteDomain = req.query?.deleteDomain === '1' || req.query?.deleteDomain === 'true'
146
+ || req.body?.deleteDomain === true;
147
+ const result = await removeApp(req.params.id, { deleteDomain });
148
+ if (!result.ok) return res.status(result.status).json({ error: result.error });
149
+ return res.json({ deleted: req.params.id, domainDeleted: result.domainDeleted, warning: result.warning ?? null });
150
+ } catch (error) {
151
+ return next(error);
152
+ }
153
+ }
154
+
155
+ /**
156
+ * PUT /api/deployments/:id/domain — link the app to a domain.
157
+ *
158
+ * The domain is created when it does not exist, and re-pointed at the app's
159
+ * port when it does. It is an ordinary domain afterwards: it appears on the
160
+ * Domains page and can be edited there.
161
+ */
162
+ async linkDomain(req, res, next) {
163
+ try {
164
+ const result = await linkDomain(req.params.id, {
165
+ domain: req.body?.domain,
166
+ ssl: req.body?.ssl === true,
167
+ });
168
+ if (!result.ok) return res.status(result.status).json({ error: result.error });
169
+ return res.json({
170
+ domain: result.domain, created: result.created, port: result.port,
171
+ ssl: result.ssl, nginxReloaded: result.nginxReloaded,
172
+ });
173
+ } catch (error) {
174
+ return next(error);
175
+ }
176
+ }
177
+
178
+ /** DELETE /api/deployments/:id/domain — forget the link; the domain itself is untouched. */
179
+ unlinkDomain(req, res, next) {
180
+ try {
181
+ const result = unlinkDomain(req.params.id);
182
+ if (!result.ok) return res.status(result.status).json({ error: result.error });
183
+ return res.json({ unlinked: true });
184
+ } catch (error) {
185
+ return next(error);
186
+ }
187
+ }
188
+
189
+ /**
190
+ * POST /api/deployments/:id/move — move the app's folder.
191
+ *
192
+ * Body `{ path }` is the PARENT folder; the app ends up in `<path>/<id>`.
193
+ * The request waits for the move: a rename is instant, a move to another
194
+ * disk copies every release.
195
+ */
196
+ async move(req, res, next) {
197
+ try {
198
+ const result = await moveApp(req.params.id, req.body?.path);
199
+ if (!result.ok) return res.status(result.status).json({ error: result.error });
200
+ return res.json({ from: result.from, to: result.to, restarted: result.restarted, warning: result.warning ?? null });
201
+ } catch (error) {
202
+ return next(error);
203
+ }
204
+ }
205
+
206
+ /** POST /api/deployments/:id/deploy */
207
+ deploy(req, res, next) {
208
+ try {
209
+ const ref = typeof req.body?.ref === 'string' && req.body.ref.trim() ? req.body.ref.trim() : null;
210
+ const started = startDeployment(req.params.id, { trigger: 'manual', ref, actor: 'dashboard' });
211
+ if (!started.ok) return res.status(started.status).json({ error: started.error, runId: started.runId ?? null });
212
+ return res.status(202).json({ runId: started.runId, status: 'running' });
213
+ } catch (error) {
214
+ return next(error);
215
+ }
216
+ }
217
+
218
+ /** POST /api/deployments/:id/rollback */
219
+ rollback(req, res, next) {
220
+ try {
221
+ const releaseId = typeof req.body?.releaseId === 'string' && req.body.releaseId ? req.body.releaseId : null;
222
+ if (releaseId !== null && !isId(releaseId)) return res.status(400).json({ error: 'Invalid release id.' });
223
+
224
+ const started = startRollback(req.params.id, { releaseId, actor: 'dashboard' });
225
+ if (!started.ok) return res.status(started.status).json({ error: started.error, runId: started.runId ?? null });
226
+ return res.status(202).json({ runId: started.runId, status: 'running' });
227
+ } catch (error) {
228
+ return next(error);
229
+ }
230
+ }
231
+
232
+ /** GET /api/deployments/:id/runs/:runId */
233
+ run(req, res, next) {
234
+ try {
235
+ const app = getApp(req.params.id);
236
+ if (!app) return res.status(404).json({ error: `No app named "${req.params.id}".` });
237
+
238
+ const run = isId(req.params.runId) ? readRun(app.id, req.params.runId) : null;
239
+ if (!run) return res.status(404).json({ error: 'No such run.' });
240
+
241
+ const log = readLogTail(app.id, run.id);
242
+ return res.json({ ...run, log: log.text, logTruncated: log.truncated });
243
+ } catch (error) {
244
+ return next(error);
245
+ }
246
+ }
247
+
248
+ /** POST /api/deployments/:id/hook-token — issue (or replace) the deploy token. */
249
+ hookToken(req, res, next) {
250
+ try {
251
+ const issued = rotateHookToken(req.params.id);
252
+ if (!issued) return res.status(404).json({ error: `No app named "${req.params.id}".` });
253
+ // The only response that ever contains it.
254
+ return res.json({ token: issued.token, tokenHint: issued.hint });
255
+ } catch (error) {
256
+ return next(error);
257
+ }
258
+ }
259
+
260
+ /** DELETE /api/deployments/:id/hook-token — the hook stops accepting this app. */
261
+ revokeHookToken(req, res, next) {
262
+ try {
263
+ if (!revokeHookToken(req.params.id)) return res.status(404).json({ error: `No app named "${req.params.id}".` });
264
+ return res.json({ revoked: true });
265
+ } catch (error) {
266
+ return next(error);
267
+ }
268
+ }
269
+
270
+ /** POST /api/deployments/:id/deploy-key — generate (or replace) the SSH deploy key. */
271
+ deployKey(req, res, next) {
272
+ try {
273
+ const key = generateDeployKey(req.params.id);
274
+ if (!key) return res.status(404).json({ error: `No app named "${req.params.id}".` });
275
+ return res.json({ publicKey: key.publicKey });
276
+ } catch (error) {
277
+ return next(error);
278
+ }
279
+ }
280
+
281
+ /** GET /api/deployments/:id/github — the workflow, the secrets and the URL. */
282
+ github(req, res, next) {
283
+ try {
284
+ const app = getApp(req.params.id);
285
+ if (!app) return res.status(404).json({ error: `No app named "${req.params.id}".` });
286
+ return res.json(githubSetupFor(app, dashboardApp));
287
+ } catch (error) {
288
+ return next(error);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * POST /api/deployments/:id/github/apply
294
+ *
295
+ * Does the GitHub steps for the user. The deploy token is issued here and
296
+ * goes straight into the repository's secrets: it is never returned, and
297
+ * the previous one stops working — which is the point of asking for a new
298
+ * setup.
299
+ */
300
+ async githubApply(req, res, next) {
301
+ try {
302
+ const app = getApp(req.params.id);
303
+ if (!app) return res.status(404).json({ error: `No app named "${req.params.id}".` });
304
+
305
+ const body = req.body ?? {};
306
+ if (!parseGithubRepo(app.repoUrl)) {
307
+ return res.status(400).json({ error: 'Automatic setup works with github.com repositories only. Use the manual steps.' });
308
+ }
309
+
310
+ // A token typed in for this is used and forgotten. Otherwise the one the
311
+ // app already clones with is tried — it often lacks write access, and
312
+ // the answer will say so.
313
+ const typed = typeof body.token === 'string' ? body.token.trim() : '';
314
+ const token = typed || (app.auth?.type === 'token' ? app.auth.token : '');
315
+ if (!validateGithubToken(token)) {
316
+ return res.status(400).json({ error: 'A GitHub token with write access to the repository is required.' });
317
+ }
318
+
319
+ const want = {
320
+ secrets: body.secrets !== false,
321
+ workflow: body.workflow !== false,
322
+ deployKey: body.deployKey !== false && app.auth?.type === 'deployKey',
323
+ };
324
+
325
+ const setup = githubSetupFor(app, dashboardApp);
326
+ const target = setup.targets.find((t) => t.id === (body.target === 'hub' ? 'hub' : 'hook'));
327
+ if (want.secrets && !target?.url) {
328
+ return res.status(409).json({
329
+ error: target?.note ?? 'There is no URL GitHub could call yet.',
330
+ reason: 'no_deploy_url',
331
+ });
332
+ }
333
+ if (want.deployKey && !setup.deployKey) {
334
+ return res.status(409).json({ error: 'Generate the deploy key first.', reason: 'no_deploy_key' });
335
+ }
336
+
337
+ let secrets = null;
338
+ if (want.secrets) {
339
+ const issued = rotateHookToken(app.id);
340
+ secrets = { EZ_DEPLOY_URL: target.url, EZ_DEPLOY_TOKEN: issued.token };
341
+ }
342
+
343
+ const result = await applyGithubSetup({
344
+ repoUrl: app.repoUrl,
345
+ branch: app.branch,
346
+ token,
347
+ secrets,
348
+ workflow: want.workflow ? { path: setup.workflowPath, content: setup.workflow } : null,
349
+ deployKey: want.deployKey ? { title: `Easy DevOps — ${app.id}`, key: setup.deployKey } : null,
350
+ });
351
+
352
+ // If the token secret did not reach GitHub, the token just issued is
353
+ // known to nobody. Revoking it leaves the app with no token rather than
354
+ // an unusable one that the UI would report as "exists".
355
+ const secretsStep = result.steps.find((s) => s.id === 'secrets');
356
+ if (want.secrets && !secretsStep?.ok) revokeHookToken(app.id);
357
+
358
+ return res.status(result.error ? 502 : 200).json({
359
+ ...result,
360
+ target: target?.id ?? null,
361
+ deployUrl: want.secrets ? target.url : null,
362
+ });
363
+ } catch (error) {
364
+ return next(error);
365
+ }
366
+ }
367
+
368
+ /** GET /api/deployments/hook */
369
+ async hook(req, res, next) {
370
+ try {
371
+ const status = await hookStatus();
372
+ const preview = hookUrl('your-app', status, getDomains());
373
+ res.json({ ...status, urlExample: preview.url, mode: preview.mode, secure: preview.secure, note: preview.note });
374
+ } catch (error) {
375
+ next(error);
376
+ }
377
+ }
378
+
379
+ /**
380
+ * PUT /api/deployments/hook
381
+ *
382
+ * Changing which domain exposes the hook rewrites that domain's nginx config
383
+ * (and the one it is moving away from). The setting is saved first because
384
+ * the config generator reads it; if nginx then rejects the result, the
385
+ * setting is put back and the previous config is already restored by
386
+ * writeConfWithTest().
387
+ */
388
+ async updateHook(req, res, next) {
389
+ try {
390
+ const body = req.body ?? {};
391
+ const config = loadConfig();
392
+ const current = hookSettings(config);
393
+ const wanted = { ...current };
394
+
395
+ if (body.enabled !== undefined) {
396
+ if (typeof body.enabled !== 'boolean') return res.status(400).json({ error: 'enabled must be true or false' });
397
+ wanted.enabled = body.enabled;
398
+ }
399
+ if (body.port !== undefined) {
400
+ const port = parseInt(body.port, 10);
401
+ const portError = validatePort(port);
402
+ if (portError) return res.status(400).json({ error: portError });
403
+ if (port === Number(config.dashboardPort)) {
404
+ return res.status(400).json({ error: 'The deploy hook cannot use the dashboard\'s port.' });
405
+ }
406
+ wanted.port = port;
407
+ }
408
+ if (body.bind !== undefined) {
409
+ if (![BIND_ALL, BIND_LOOPBACK].includes(body.bind)) {
410
+ return res.status(400).json({ error: `bind must be ${BIND_LOOPBACK} or ${BIND_ALL}` });
411
+ }
412
+ wanted.bind = body.bind;
413
+ }
414
+ if (body.domain !== undefined) {
415
+ if (body.domain === null || body.domain === '') {
416
+ wanted.domain = null;
417
+ } else {
418
+ const record = findDomain(String(body.domain));
419
+ if (!record) return res.status(400).json({ error: `No domain named "${body.domain}".` });
420
+ wanted.domain = record.name;
421
+ }
422
+ }
423
+
424
+ saveConfig({ ...config, deployHook: wanted });
425
+
426
+ // Which domain configs now differ from what is on disk.
427
+ const before = current.enabled ? current.domain : null;
428
+ const after = wanted.enabled ? wanted.domain : null;
429
+ const portMoved = current.port !== wanted.port;
430
+ const touched = [...new Set([
431
+ ...(before !== after ? [before, after] : []),
432
+ ...(portMoved && after ? [after] : []),
433
+ ].filter(Boolean))];
434
+
435
+ const applied = [];
436
+ for (const name of touched) {
437
+ const record = findDomain(name);
438
+ // A disabled domain has no live config to rewrite; it picks the
439
+ // location up when it is enabled again.
440
+ if (!record || record.enabled === false) continue;
441
+
442
+ const result = await writeConfWithTest(record);
443
+ if (!result.ok) {
444
+ saveConfig({ ...loadConfig(), deployHook: current });
445
+ // Put back any config already rewritten for the new setting.
446
+ for (const done of applied) {
447
+ const again = findDomain(done);
448
+ if (again) await writeConfWithTest(again);
449
+ }
450
+ return res.status(500).json({
451
+ error: `nginx rejected the configuration for ${name}, so the deploy hook setting was not changed.`,
452
+ detail: result.error,
453
+ });
454
+ }
455
+ applied.push(name);
456
+ }
457
+
458
+ let nginxReloaded = null;
459
+ if (applied.length > 0) {
460
+ const reloaded = await reloadNginx();
461
+ nginxReloaded = reloaded.ok;
462
+ }
463
+
464
+ const status = await hookStatus();
465
+ const preview = hookUrl('your-app', status, getDomains());
466
+ return res.json({
467
+ ...status,
468
+ urlExample: preview.url, mode: preview.mode, secure: preview.secure, note: preview.note,
469
+ nginxReloaded,
470
+ // The listener re-reads the setting on a timer, in another process.
471
+ appliesWithinSeconds: 10,
472
+ });
473
+ } catch (error) {
474
+ return next(error);
475
+ }
476
+ }
477
+ }
478
+
479
+ export default DeploymentsController;