easy-devops 1.3.5 → 1.4.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 (69) hide show
  1. package/README.md +1 -0
  2. package/dist/ui/assets/index-Bu7af-Kj.css +1 -0
  3. package/dist/ui/assets/index-gndgYe3K.js +532 -0
  4. package/dist/ui/assets/socket-Bv0wCEgi.js +65 -0
  5. package/dist/ui/index.html +2 -2
  6. package/package.json +2 -2
  7. package/src/cli/index.js +8 -0
  8. package/src/cli/managers/domain-manager.js +37 -6
  9. package/src/cli/managers/nginx-manager.js +14 -5
  10. package/src/cli/managers/node-manager.js +19 -13
  11. package/src/cli/managers/ssl-manager.js +89 -26
  12. package/src/cli/menu.js +8 -2
  13. package/src/cli/menus/cleanup.js +4 -2
  14. package/src/cli/menus/dashboard.js +22 -15
  15. package/src/cli/menus/hub.js +381 -0
  16. package/src/cli/menus/runtime.js +12 -0
  17. package/src/cli/menus/service.js +28 -10
  18. package/src/cli/menus/settings.js +46 -12
  19. package/src/cli/menus/uninstall.js +13 -5
  20. package/src/cli/menus/update.js +24 -14
  21. package/src/cli/ui/page.js +123 -0
  22. package/src/core/cert-operations.js +34 -4
  23. package/src/core/cert-reader.js +67 -22
  24. package/src/core/cert-renewal.js +65 -9
  25. package/src/core/cert-suggest.js +120 -0
  26. package/src/core/cleanup.js +221 -1
  27. package/src/core/cloudflare-ips.js +161 -0
  28. package/src/core/daemon/ipc.js +1 -1
  29. package/src/core/daemon/lock.js +296 -9
  30. package/src/core/dashboardProcess.js +134 -6
  31. package/src/core/deploy/apps.js +36 -62
  32. package/src/core/deploy/deployKey.js +331 -0
  33. package/src/core/deploy/domainLink.js +280 -23
  34. package/src/core/deploy/engine.js +382 -63
  35. package/src/core/deploy/ezfile.js +496 -29
  36. package/src/core/deploy/githubApi.js +100 -13
  37. package/src/core/deploy/hubCommands.js +158 -18
  38. package/src/core/deploy/status.js +28 -1
  39. package/src/core/domains-db.js +1 -0
  40. package/src/core/hub/agent.js +238 -32
  41. package/src/core/hub/deployProgress.js +411 -0
  42. package/src/core/hubConnect.js +205 -0
  43. package/src/core/hubPermissions.js +48 -10
  44. package/src/core/jobs/bus.js +1 -1
  45. package/src/core/jobs/owner.js +268 -6
  46. package/src/core/nginx-conf-generator.js +124 -19
  47. package/src/core/notifications/claim.js +26 -3
  48. package/src/core/permissions.js +277 -59
  49. package/src/core/platform.js +48 -2
  50. package/src/core/runner.js +96 -40
  51. package/src/core/ssl/preflight.js +548 -0
  52. package/src/core/ssl/progress.js +196 -0
  53. package/src/core/ssl-issuer.js +502 -148
  54. package/src/core/validators.js +24 -0
  55. package/src/dashboard/controllers/authController.js +12 -5
  56. package/src/dashboard/controllers/deploymentsController.js +76 -11
  57. package/src/dashboard/controllers/domainsController.js +35 -1
  58. package/src/dashboard/controllers/hubController.js +4 -3
  59. package/src/dashboard/controllers/settingsController.js +73 -68
  60. package/src/dashboard/controllers/sslController.js +135 -15
  61. package/src/dashboard/public/js/app.js +42 -7
  62. package/src/dashboard/routes/deployments.js +2 -0
  63. package/src/dashboard/routes/domains.js +1 -0
  64. package/src/dashboard/server.js +73 -8
  65. package/src/dashboard/socketManager.js +19 -25
  66. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  67. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  68. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  69. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
@@ -95,6 +95,30 @@ export function validatePositiveInteger(val, field) {
95
95
  return null;
96
96
  }
97
97
 
98
+ /**
99
+ * Validates a strictly boolean field. `undefined`/`null` mean "not supplied"
100
+ * and are accepted, so older clients and stored domains keep working.
101
+ * @param {unknown} value
102
+ * @param {string} field Human-readable field name for the error message
103
+ * @returns {string|null}
104
+ */
105
+ export function validateBoolean(value, field) {
106
+ if (value === undefined || value === null) return null;
107
+ if (typeof value !== 'boolean') {
108
+ return `Invalid ${field}: must be true or false`;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Validates the per-domain `behindCloudflare` option.
115
+ * @param {unknown} value
116
+ * @returns {string|null}
117
+ */
118
+ export function validateBehindCloudflare(value) {
119
+ return validateBoolean(value, 'behindCloudflare');
120
+ }
121
+
98
122
  /**
99
123
  * Validates the hub URL portion of a connection string.
100
124
  * Accepts an http/https URL or a bare host, optionally with a port.
@@ -16,11 +16,12 @@
16
16
  * 3. Passwords are stored as scrypt hashes (core/passwords.js). An existing
17
17
  * plain-text password still works, and is migrated on the next login.
18
18
  * 4. Login is rate limited per IP.
19
- * 5. First-run setup requires a one-time code printed on the server
20
- * (core/setupCode.js). This endpoint is public by necessity, so without
21
- * it whoever reaches a freshly started dashboard first owns it. The code
22
- * itself is never in a response — a client learns only whether one is
23
- * required.
19
+ * 5. Setting the first password requires a one-time code printed on the
20
+ * server (core/setupCode.js). This endpoint is public by necessity, so
21
+ * without it whoever reaches a freshly started dashboard first owns it.
22
+ * The code itself is never in a response — a client learns only whether
23
+ * one is required. Choosing "no password" needs none: loopback bind AND
24
+ * loopback request is already a stronger constraint.
24
25
  */
25
26
 
26
27
  import {
@@ -231,6 +232,12 @@ class AuthController {
231
232
  }
232
233
 
233
234
  saveConfig({ ...loadConfig(), dashboardAuth: AUTH_MODES.NONE });
235
+
236
+ // Setup is done on this path too, so the code has no further purpose.
237
+ // Removed for the same reason as after a password: an outstanding
238
+ // credential nobody needs is one more thing that can be read.
239
+ setupCode.clear();
240
+
234
241
  return res.json({ ok: true, authMode: AUTH_MODES.NONE });
235
242
  }
236
243
 
@@ -30,16 +30,21 @@ import { loadChannels } from '../../core/notifier.js';
30
30
 
31
31
  import {
32
32
  getApp, createApp, updateApp, dashboardApp,
33
- rotateHookToken, revokeHookToken, generateDeployKey,
33
+ rotateHookToken, revokeHookToken,
34
34
  DEFAULT_KEEP_RELEASES, MIN_KEEP_RELEASES, MAX_KEEP_RELEASES,
35
35
  } from '../../core/deploy/apps.js';
36
36
  import { startDeployment, startRollback, removeRelease, removeApp, moveApp } from '../../core/deploy/engine.js';
37
37
  import { readRun, readLogTail, isId, deployRoot } from '../../core/deploy/store.js';
38
38
  import { linkDomain, unlinkDomain } from '../../core/deploy/domainLink.js';
39
+ import { resolveOpId, createSslProgress } from '../../core/ssl/progress.js';
40
+ import { publish } from '../../core/jobs/bus.js';
39
41
  import { describeApps, describeAppDetail } from '../../core/deploy/status.js';
40
42
  import { hookSettings } from '../../core/deploy/hookServer.js';
41
43
  import { hookUrl } from '../../core/deploy/github.js';
42
- import { githubSetupFor } from '../../core/deploy/hubCommands.js';
44
+ import {
45
+ githubSetupFor, generateKeyForApp, wantsGeneratedKey, regenerateAppDeployKey, addAppDeployKeyToGithub,
46
+ } from '../../core/deploy/hubCommands.js';
47
+ import { testDeployKey } from '../../core/deploy/deployKey.js';
43
48
  import { applyGithubSetup, parseGithubRepo, validateGithubToken } from '../../core/deploy/githubApi.js';
44
49
  import { EZ_FILE_LOCATIONS } from '../../core/deploy/ezfile.js';
45
50
 
@@ -109,9 +114,14 @@ class DeploymentsController {
109
114
  /** POST /api/deployments */
110
115
  create(req, res, next) {
111
116
  try {
112
- const result = createApp(req.body ?? {});
117
+ const body = req.body ?? {};
118
+ const result = createApp(body);
113
119
  if (!result.ok) return res.status(result.status).json(errorBody(result));
114
- return res.status(201).json(dashboardApp(result.app));
120
+ // Creating an app never starts a deployment. The key, when asked for, is
121
+ // generated in this same request; a failure still leaves a usable app.
122
+ const extra = wantsGeneratedKey(body) ? generateKeyForApp(result.app.id) : {};
123
+ const app = getApp(result.app.id) ?? result.app;
124
+ return res.status(201).json({ ...dashboardApp(app), ...extra });
115
125
  } catch (error) {
116
126
  return next(error);
117
127
  }
@@ -169,14 +179,39 @@ class DeploymentsController {
169
179
  */
170
180
  async linkDomain(req, res, next) {
171
181
  try {
182
+ const { opId, error } = resolveOpId(req.body?.opId);
183
+ if (error) return res.status(400).json({ error: 'invalid_opId', detail: error });
184
+
185
+ const domainName = String(req.body?.domain ?? '').trim().toLowerCase();
186
+ const progress = createSslProgress({
187
+ opId,
188
+ domain: domainName,
189
+ onEvent: (event) => publish('ssl:progress', event),
190
+ });
191
+
192
+ // Issuing is synchronous here, exactly like POST /api/ssl/create, but the
193
+ // same stage feed reaches the dialog through ssl:progress while it runs.
172
194
  const result = await linkDomain(req.params.id, {
173
195
  domain: req.body?.domain,
174
- ssl: req.body?.ssl === true,
196
+ www: req.body?.www,
197
+ ssl: req.body?.ssl,
198
+ redirect: req.body?.redirect,
199
+ behindCloudflare: req.body?.behindCloudflare,
200
+ }, {
201
+ onProgress: (stage, status, detail) => progress.report(stage, status, detail),
175
202
  });
176
- if (!result.ok) return res.status(result.status).json({ error: result.error });
203
+ if (!result.ok) return res.status(result.status).json({ error: result.error, opId });
177
204
  return res.json({
178
- domain: result.domain, created: result.created, port: result.port,
179
- ssl: result.ssl, nginxReloaded: result.nginxReloaded,
205
+ ok: result.ok,
206
+ opId,
207
+ domain: result.domain,
208
+ created: result.created,
209
+ port: result.port,
210
+ www: result.www,
211
+ behindCloudflare: result.behindCloudflare,
212
+ ssl: result.ssl,
213
+ redirect: result.redirect,
214
+ nginxReloaded: result.nginxReloaded,
180
215
  });
181
216
  } catch (error) {
182
217
  return next(error);
@@ -289,9 +324,39 @@ class DeploymentsController {
289
324
  /** POST /api/deployments/:id/deploy-key — generate (or replace) the SSH deploy key. */
290
325
  deployKey(req, res, next) {
291
326
  try {
292
- const key = generateDeployKey(req.params.id);
293
- if (!key) return res.status(404).json({ error: `No app named "${req.params.id}".` });
294
- return res.json({ publicKey: key.publicKey });
327
+ const result = regenerateAppDeployKey(req.params.id);
328
+ if (!result.ok) return res.status(result.status).json({ error: result.error });
329
+ return res.json(result.value);
330
+ } catch (error) {
331
+ return next(error);
332
+ }
333
+ }
334
+
335
+ /**
336
+ * POST /api/deployments/:id/deploy-key/test — git ls-remote with the app's
337
+ * key. A completed test is 200 even when it says the key does not work; the
338
+ * earlier 404/400/409/500 statuses are passed through.
339
+ */
340
+ async deployKeyTest(req, res, next) {
341
+ try {
342
+ const result = await testDeployKey(req.params.id);
343
+ return res.status(result.status ?? 200).json(result);
344
+ } catch (error) {
345
+ return next(error);
346
+ }
347
+ }
348
+
349
+ /**
350
+ * POST /api/deployments/:id/deploy-key/github — add the public key to GitHub
351
+ * read-only. The token is typed for this request, used once and forgotten;
352
+ * when omitted the app's own token is tried, exactly as githubApply does.
353
+ */
354
+ async deployKeyGithub(req, res, next) {
355
+ try {
356
+ const result = await addAppDeployKeyToGithub(req.params.id, req.body?.token);
357
+ const { status, ...body } = result;
358
+ if (!result.ok) return res.status(status ?? 422).json(body);
359
+ return res.json(body);
295
360
  } catch (error) {
296
361
  return next(error);
297
362
  }
@@ -6,10 +6,11 @@ import { getDomains, saveDomains, findDomain, createDomain, DOMAIN_DEFAULTS } fr
6
6
  import { writeConfWithTest } from '../../core/nginx-apply.js';
7
7
  import { getDefaultCertPaths } from '../../core/nginx-conf-generator.js';
8
8
  import { getCertExpiry } from '../../core/cert-reader.js';
9
+ import { findCertificateForDomain } from '../../core/cert-suggest.js';
9
10
  import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk, hasBackslashPath } from '../../core/platform.js';
10
11
  import {
11
12
  validateDomainName, validatePort, validateUpstreamType,
12
- validateMaxBodySize,
13
+ validateMaxBodySize, validateBehindCloudflare,
13
14
  } from '../../core/validators.js';
14
15
  import { getDomainNotifConfig, saveDomainNotifConfig } from '../../core/domainNotifier.js';
15
16
 
@@ -117,6 +118,11 @@ class DomainsController {
117
118
  return res.status(400).json({ error: maxSizeError });
118
119
  }
119
120
 
121
+ const cloudflareError = validateBehindCloudflare(body.behindCloudflare);
122
+ if (cloudflareError) {
123
+ return res.status(400).json({ error: cloudflareError });
124
+ }
125
+
120
126
  // Check for duplicate
121
127
  if (findDomain(body.name)) {
122
128
  return res.status(409).json({ error: `Domain already exists: ${body.name}` });
@@ -158,6 +164,7 @@ class DomainsController {
158
164
  customLocations: body.advanced?.customLocations ?? '',
159
165
  },
160
166
  wildcard: body.wildcard ?? false,
167
+ behindCloudflare: body.behindCloudflare ?? false,
161
168
  enabled: true,
162
169
  });
163
170
 
@@ -219,6 +226,14 @@ class DomainsController {
219
226
  }
220
227
  }
221
228
 
229
+ // Validate behindCloudflare if provided
230
+ if (body.behindCloudflare !== undefined) {
231
+ const cloudflareError = validateBehindCloudflare(body.behindCloudflare);
232
+ if (cloudflareError) {
233
+ return res.status(400).json({ error: cloudflareError });
234
+ }
235
+ }
236
+
222
237
  // name is immutable — merge everything except name, configFile, and notifications
223
238
  const { name: _ignored, configFile: _cf, notifications, ...updates } = body;
224
239
 
@@ -419,6 +434,25 @@ class DomainsController {
419
434
  }
420
435
  }
421
436
 
437
+ /**
438
+ * Reports an existing certificate that could serve this domain, so the edit
439
+ * modal can offer to fill the cert/key paths in. Read-only: nothing is
440
+ * changed until the operator accepts and saves.
441
+ */
442
+ async sslSuggestion(req, res, next) {
443
+ try {
444
+ const { name } = req.params;
445
+ if (!name || !name.trim()) {
446
+ return res.status(400).json({ error: 'A domain name is required' });
447
+ }
448
+ // The deployments link dialog asks about a domain before it exists, so
449
+ // an unknown name is not an error: the answer is simply "not found".
450
+ res.json(await findCertificateForDomain(name));
451
+ } catch (error) {
452
+ next(error);
453
+ }
454
+ }
455
+
422
456
  async updateNotifications(req, res, next) {
423
457
  try {
424
458
  saveDomainNotifConfig(req.params.name, req.body ?? {});
@@ -1,8 +1,9 @@
1
1
  // src/dashboard/controllers/hubController.js
2
2
  //
3
- // Thin HTTP layer over core/hubLink.js. All link parsing, persistence and
4
- // permission logic lives in core so a future CLI menu can reuse it — this
5
- // controller only translates between HTTP and that module.
3
+ // Thin HTTP layer over core/hubLink.js and core/hub/agent.js. Link parsing,
4
+ // persistence and permission logic live in core so other callers can reuse
5
+ // them — this controller only translates between HTTP and those modules, and
6
+ // decides which process may own the agent.
6
7
  //
7
8
  // The hub issues connection strings; this server never generates them.
8
9
 
@@ -1,6 +1,5 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import os from 'os';
4
3
  import crypto from 'crypto';
5
4
  import {
6
5
  loadConfig, saveConfig, BIND_ALL, BIND_LOOPBACK, BIND_LOOPBACK_V6,
@@ -12,13 +11,29 @@ import { validatePort, validateEmail } from '../../core/validators.js';
12
11
  import {
13
12
  getAutoRenewSettings, normalizeAutoRenewDays, MIN_AUTO_RENEW_DAYS, MAX_AUTO_RENEW_DAYS,
14
13
  } from '../../core/cert-renewal.js';
15
- import { run, runWithStdin } from '../../core/shell.js';
16
- import { checkPermissionsConfigured } from '../../core/permissions.js';
17
- import { dbGet, dbSet } from '../../core/db.js';
14
+ import { isWindows } from '../../core/platform.js';
15
+ import {
16
+ checkPermissionsConfigured, buildSetupScript, deriveOwnDirs,
17
+ } from '../../core/permissions.js';
18
+ import { dbGet } from '../../core/db.js';
18
19
  import { deployRoot, defaultDeployRoot, validateDeployDir } from '../../core/deploy/store.js';
19
20
  import { saveDomains } from '../../core/domains-db.js';
20
21
  import { loadChannels, saveChannels, sendNotification } from '../../core/notifier.js';
21
22
 
23
+ /**
24
+ * The UI a configuration selects, resolved identically on read and write.
25
+ *
26
+ * Anything but an explicit `new` reads as `classic`, which is also the value a
27
+ * client must assume when the field is absent. GET and POST both go through
28
+ * here so they can never disagree about the same config.
29
+ *
30
+ * @param {Object} config
31
+ * @returns {string} One of UI_MODES
32
+ */
33
+ function resolveDashboardUi(config) {
34
+ return config?.dashboardUi === UI_MODES.NEW ? UI_MODES.NEW : UI_MODES.CLASSIC;
35
+ }
36
+
22
37
  class SettingsController {
23
38
  get(req, res) {
24
39
  try {
@@ -48,13 +63,13 @@ class SettingsController {
48
63
  dashboardAuth: effectiveAuthMode(config),
49
64
  // Anything unrecognised reads as classic, which is also the
50
65
  // default. The value only takes effect on restart.
51
- dashboardUi: config.dashboardUi === UI_MODES.NEW ? UI_MODES.NEW : UI_MODES.CLASSIC,
66
+ dashboardUi: resolveDashboardUi(config),
52
67
  // Whether the UI may offer 'none' at all: the bind must be loopback
53
68
  // and the person asking must be on this machine.
54
69
  canUseNoPassword: isLoopbackBind(dashboardBindAddress) &&
55
70
  isLoopbackAddress(req.ip ?? req.socket?.remoteAddress),
56
71
  hasPassword,
57
- platform: process.platform === 'win32' ? 'win32' : 'linux',
72
+ platform: isWindows ? 'win32' : 'linux',
58
73
  });
59
74
  } catch (err) {
60
75
  res.status(500).json({ error: 'Internal server error' });
@@ -208,7 +223,9 @@ class SettingsController {
208
223
  success: true,
209
224
  needsRestart,
210
225
  dashboardAuth: effectiveAuthMode({ ...currentConfig, ...updates }),
211
- dashboardUi: updates.dashboardUi ?? currentConfig.dashboardUi,
226
+ // Resolved by the same helper GET uses, so a stored value GET
227
+ // would read as classic cannot be echoed back as something else.
228
+ dashboardUi: resolveDashboardUi({ ...currentConfig, ...updates }),
212
229
  });
213
230
  } catch (err) {
214
231
  res.status(500).json({ error: 'Internal server error' });
@@ -216,7 +233,7 @@ class SettingsController {
216
233
  }
217
234
 
218
235
  async getPermissions(req, res) {
219
- if (process.platform === 'win32') return res.json({ configured: true });
236
+ if (isWindows) return res.json({ configured: true });
220
237
  try {
221
238
  const configured = await checkPermissionsConfigured();
222
239
  res.json({ configured });
@@ -225,72 +242,60 @@ class SettingsController {
225
242
  }
226
243
  }
227
244
 
228
- async setupPermissions(req, res) {
229
- if (process.platform === 'win32') {
245
+ /**
246
+ * POST /api/settings/permissions/setup
247
+ *
248
+ * Reports the sudoers state and the exact terminal commands that install
249
+ * the rules. It INSTALLS NOTHING and never accepts a password:
250
+ *
251
+ * - the request body is deliberately not read at all. An older client
252
+ * that still sends `password` has it ignored, never stored, never
253
+ * forwarded;
254
+ * - no privileged command runs here. `checkPermissionsConfigured()` only
255
+ * asks sudo whether it would prompt (`sudo -n`);
256
+ * - the operator pastes the commands into their own terminal, where sudo
257
+ * asks THEM for their password. That is the only place it is typed.
258
+ *
259
+ * `deps` exists so a test can drive both outcomes without a real dashboard
260
+ * and without ever running sudo.
261
+ *
262
+ * @param {Object} req
263
+ * @param {Object} res
264
+ * @param {Object} [deps]
265
+ * @param {boolean} [deps.isWindows]
266
+ * @param {() => Promise<boolean>} [deps.checkConfigured]
267
+ * @param {string} [deps.user] Account the rules are written for; defaults
268
+ * to the one this process runs as (injectable for tests)
269
+ */
270
+ async setupPermissions(req, res, deps = {}) {
271
+ if (deps.isWindows ?? isWindows) {
230
272
  return res.status(400).json({ error: 'Not applicable on Windows' });
231
273
  }
232
274
 
233
- const { password } = req.body ?? {};
234
- if (!password || typeof password !== 'string') {
235
- return res.status(400).json({ error: 'Password is required' });
236
- }
237
-
238
- const whichResult = await run('which nginx');
239
- if (!whichResult.success || !whichResult.stdout.trim()) {
240
- return res.status(500).json({ error: 'nginx not found. Is nginx installed?' });
241
- }
242
- const nginxPath = whichResult.stdout.trim().split('\n')[0].trim();
243
- const user = os.userInfo().username;
244
-
245
- const sudoRules = [
246
- '/usr/bin/systemctl start nginx',
247
- '/usr/bin/systemctl stop nginx',
248
- '/usr/bin/systemctl reload nginx',
249
- '/usr/bin/systemctl restart nginx',
250
- '/usr/bin/systemctl',
251
- nginxPath,
252
- `${nginxPath} -t`,
253
- `${nginxPath} -s reload`,
254
- `${nginxPath} -s stop`,
255
- `${nginxPath} -s quit`,
256
- '/usr/bin/certbot',
257
- '/usr/bin/mkdir',
258
- '/usr/bin/cp',
259
- '/usr/bin/chmod',
260
- '/usr/bin/chown',
261
- '/usr/bin/tee',
262
- ].join(', ');
263
-
264
- const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ${sudoRules}\n`;
265
-
266
- const tmpFile = path.join('/tmp', `easy-devops-sudoers-${Date.now()}`);
267
275
  try {
268
- await fs.writeFile(tmpFile, sudoersContent, { mode: 0o600 });
269
- } catch (err) {
270
- return res.status(500).json({ error: 'Failed to write temp file', output: err.message });
271
- }
276
+ const checkConfigured = deps.checkConfigured ?? checkPermissionsConfigured;
272
277
 
273
- const setupCmd = [
274
- `mkdir -p /etc/easy-devops /var/log/easy-devops`,
275
- `chown ${user}:${user} /etc/easy-devops /var/log/easy-devops`,
276
- `chown -R ${user}:${user} /etc/nginx/conf.d 2>/dev/null || true`,
277
- `cp '${tmpFile}' /etc/sudoers.d/easy-devops`,
278
- `chmod 440 /etc/sudoers.d/easy-devops`,
279
- ].join(' && ');
280
-
281
- const result = await runWithStdin('sudo', ['-S', 'bash', '-c', setupCmd], password + '\n');
282
- await fs.unlink(tmpFile).catch(() => {});
283
-
284
- if (!result.success) {
285
- const output = result.stderr || result.stdout;
286
- const wrongPassword = output.includes('incorrect password') || output.includes('Sorry, try again') || output.includes('3 incorrect');
287
- return res.status(wrongPassword ? 401 : 500).json({
288
- error: wrongPassword ? 'Incorrect password' : 'Setup failed',
289
- output,
290
- });
291
- }
278
+ const { ownDirs, refused } = deriveOwnDirs(loadConfig());
279
+ const script = buildSetupScript({ user: deps.user, ownDirs });
280
+
281
+ let configured = false;
282
+ try {
283
+ configured = await checkConfigured();
284
+ } catch { /* reported as not configured, which is actionable */ }
285
+
286
+ if (!script.ok) {
287
+ return res.status(400).json({
288
+ configured,
289
+ error: script.reason,
290
+ commands: [],
291
+ refusedDirs: refused,
292
+ });
293
+ }
292
294
 
293
- res.json({ success: true });
295
+ res.json({ configured, commands: script.lines, refusedDirs: refused });
296
+ } catch (err) {
297
+ res.status(500).json({ error: 'Internal server error' });
298
+ }
294
299
  }
295
300
 
296
301
  backup(req, res) {