easy-devops 1.2.1 → 1.3.1

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-CMRzkIKj.css +1 -0
  3. package/dist/ui/assets/index-DEouL3IK.js +452 -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 +222 -47
  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 +80 -61
  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 +288 -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 +10 -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,361 @@
1
+ /**
2
+ * core/deploy/ezfile.js
3
+ *
4
+ * Works out HOW a project is installed, built and started.
5
+ *
6
+ * Three sources, in order of precedence:
7
+ *
8
+ * 1. overrides — values set on the app in the dashboard or the Hub
9
+ * 2. ez.json — a file in the repository, versioned with the code
10
+ * 3. defaults — read from package.json, so a plain Node project deploys
11
+ * with no configuration at all
12
+ *
13
+ * ez.json is optional. When it gives `install`, `build` and `start`, those
14
+ * commands are run exactly as written, whatever the language — which is what
15
+ * lets a Python or Go project deploy before anyone has written auto-detection
16
+ * for it. Detection only ever saves writing the file.
17
+ *
18
+ * Pure: no filesystem, no shell, no config. The engine reads the files and
19
+ * hands their contents in, so every rule here can be tested directly.
20
+ *
21
+ * ── ez.json ──────────────────────────────────────────────────────────────────
22
+ *
23
+ * {
24
+ * "install": "npm ci", string | string[] | false
25
+ * "build": "npm run build", string | string[] | false
26
+ * "start": "node server.js", string
27
+ * "port": 3000, the port the app listens on
28
+ * "health": "/healthz", string, or { "path": "/healthz", "timeout": 60 }
29
+ * "hooks": { "pre": "...", "post": "..." } string | string[]
30
+ * }
31
+ *
32
+ * `false` (or an empty string) switches a step off — "this project has no
33
+ * build" is a real answer, and different from "work it out for me".
34
+ */
35
+
36
+ /** Where ez.json may live, relative to the repository root, first match wins. */
37
+ export const EZ_FILE_LOCATIONS = Object.freeze(['ez.json', 'deploy/ez.json', '.deploy/ez.json']);
38
+
39
+ export const DEFAULT_HEALTH_PATH = '/';
40
+ export const DEFAULT_HEALTH_TIMEOUT_S = 60;
41
+ export const MAX_HEALTH_TIMEOUT_S = 600;
42
+
43
+ const COMMAND_FIELDS = Object.freeze(['install', 'build']);
44
+ const KNOWN_KEYS = Object.freeze(['$schema', 'name', 'install', 'build', 'start', 'port', 'health', 'hooks']);
45
+ const MAX_COMMAND_LENGTH = 2000;
46
+
47
+ /** @returns {boolean} */
48
+ function isPlainObject(v) {
49
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
50
+ }
51
+
52
+ /**
53
+ * Normalises a command field to a list of command lines.
54
+ *
55
+ * @param {*} value string | string[] | false | null | undefined
56
+ * @returns {{ commands: string[]|null, disabled: boolean, error: string|null }}
57
+ * `commands: null` with `disabled: false` means "not specified here".
58
+ */
59
+ export function normalizeCommands(value) {
60
+ if (value === undefined || value === null) return { commands: null, disabled: false, error: null };
61
+ if (value === false) return { commands: [], disabled: true, error: null };
62
+
63
+ const list = Array.isArray(value) ? value : [value];
64
+ const out = [];
65
+ for (const item of list) {
66
+ if (typeof item !== 'string') return { commands: null, disabled: false, error: 'must be a string, a list of strings, or false' };
67
+ const trimmed = item.trim();
68
+ if (trimmed.length > MAX_COMMAND_LENGTH) return { commands: null, disabled: false, error: `is longer than ${MAX_COMMAND_LENGTH} characters` };
69
+ // A newline would let one field smuggle a second command past whoever reviews it.
70
+ if (/[\r\n\0]/.test(trimmed)) return { commands: null, disabled: false, error: 'must be a single line — use a list for several commands' };
71
+ if (trimmed) out.push(trimmed);
72
+ }
73
+
74
+ // An empty string or an empty list is the same answer as `false`.
75
+ if (out.length === 0) return { commands: [], disabled: true, error: null };
76
+ return { commands: out, disabled: false, error: null };
77
+ }
78
+
79
+ /**
80
+ * Validates a port value.
81
+ * @returns {number|null} The port, or null when it is not usable
82
+ */
83
+ export function normalizePort(value) {
84
+ const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
85
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1 || n > 65535) return null;
86
+ return n;
87
+ }
88
+
89
+ /** @returns {string|null} A path starting with `/`, or null when not usable */
90
+ export function normalizeHealthPath(value) {
91
+ if (typeof value !== 'string') return null;
92
+ const p = value.trim();
93
+ if (!p.startsWith('/') || p.length > 500 || /[\s\0]/.test(p)) return null;
94
+ return p;
95
+ }
96
+
97
+ /**
98
+ * Parses and validates the contents of an ez.json file.
99
+ *
100
+ * Errors make the file unusable and stop the deployment: silently ignoring a
101
+ * mistyped `port` would deploy something the author did not ask for. Unknown
102
+ * keys are only warnings — a newer ez.json should still deploy on an older
103
+ * Easy DevOps.
104
+ *
105
+ * @param {string} text The file's raw contents
106
+ * @returns {{ ok: boolean, value: Object|null, errors: string[], warnings: string[] }}
107
+ */
108
+ export function parseEzFile(text) {
109
+ const errors = [];
110
+ const warnings = [];
111
+
112
+ let raw;
113
+ try {
114
+ raw = JSON.parse(String(text).replace(/^\uFEFF/, ''));
115
+ } catch (err) {
116
+ return { ok: false, value: null, errors: [`ez.json is not valid JSON: ${err.message}`], warnings };
117
+ }
118
+ if (!isPlainObject(raw)) {
119
+ return { ok: false, value: null, errors: ['ez.json must contain a JSON object'], warnings };
120
+ }
121
+
122
+ for (const key of Object.keys(raw)) {
123
+ if (!KNOWN_KEYS.includes(key)) warnings.push(`ez.json: unknown key "${key}" was ignored`);
124
+ }
125
+
126
+ const value = {};
127
+
128
+ for (const field of COMMAND_FIELDS) {
129
+ const n = normalizeCommands(raw[field]);
130
+ if (n.error) errors.push(`ez.json: "${field}" ${n.error}`);
131
+ else if (n.commands !== null) value[field] = n.commands;
132
+ }
133
+
134
+ if (raw.start !== undefined && raw.start !== null) {
135
+ const n = normalizeCommands(raw.start);
136
+ if (n.error) errors.push(`ez.json: "start" ${n.error}`);
137
+ else if (n.commands.length > 1) errors.push('ez.json: "start" must be a single command — it is the long-running process');
138
+ else if (n.commands.length === 1) value.start = n.commands[0];
139
+ else errors.push('ez.json: "start" cannot be empty or false — a deployment needs something to run');
140
+ }
141
+
142
+ if (raw.port !== undefined && raw.port !== null) {
143
+ const port = normalizePort(raw.port);
144
+ if (port === null) errors.push('ez.json: "port" must be a whole number from 1 to 65535');
145
+ else value.port = port;
146
+ }
147
+
148
+ if (raw.health !== undefined && raw.health !== null) {
149
+ const h = typeof raw.health === 'string' ? { path: raw.health } : raw.health;
150
+ if (!isPlainObject(h)) {
151
+ errors.push('ez.json: "health" must be a path like "/healthz" or an object with "path"');
152
+ } else {
153
+ if (h.path !== undefined) {
154
+ const p = normalizeHealthPath(h.path);
155
+ if (p === null) errors.push('ez.json: "health.path" must start with "/" and contain no spaces');
156
+ else value.healthPath = p;
157
+ }
158
+ if (h.timeout !== undefined) {
159
+ const t = Number(h.timeout);
160
+ if (!Number.isInteger(t) || t < 1 || t > MAX_HEALTH_TIMEOUT_S) {
161
+ errors.push(`ez.json: "health.timeout" must be a whole number of seconds from 1 to ${MAX_HEALTH_TIMEOUT_S}`);
162
+ } else {
163
+ value.healthTimeout = t;
164
+ }
165
+ }
166
+ }
167
+ }
168
+
169
+ if (raw.hooks !== undefined && raw.hooks !== null) {
170
+ if (!isPlainObject(raw.hooks)) {
171
+ errors.push('ez.json: "hooks" must be an object with "pre" and/or "post"');
172
+ } else {
173
+ for (const key of Object.keys(raw.hooks)) {
174
+ if (key !== 'pre' && key !== 'post') warnings.push(`ez.json: unknown hook "${key}" was ignored`);
175
+ }
176
+ for (const hook of ['pre', 'post']) {
177
+ const n = normalizeCommands(raw.hooks[hook]);
178
+ if (n.error) errors.push(`ez.json: "hooks.${hook}" ${n.error}`);
179
+ else if (n.commands !== null) value[hook] = n.commands;
180
+ }
181
+ }
182
+ }
183
+
184
+ return { ok: errors.length === 0, value: errors.length === 0 ? value : null, errors, warnings };
185
+ }
186
+
187
+ /**
188
+ * Defaults for a Node project, read from its package.json.
189
+ *
190
+ * @param {Object|null} pkg Parsed package.json, or null when there is none
191
+ * @param {{ packageLock?: boolean, yarnLock?: boolean, pnpmLock?: boolean }} [files] Lockfiles present
192
+ * @returns {{ install?: string[], build?: string[], start?: string }}
193
+ */
194
+ export function defaultsFromPackageJson(pkg, files = {}) {
195
+ if (!isPlainObject(pkg)) return {};
196
+
197
+ const out = {};
198
+ const scripts = isPlainObject(pkg.scripts) ? pkg.scripts : {};
199
+
200
+ // The lockfile decides the tool, and `ci`-style installs are used when one
201
+ // exists: a deployment should build what was committed, not re-resolve.
202
+ if (files.pnpmLock) out.install = ['pnpm install --frozen-lockfile'];
203
+ else if (files.yarnLock) out.install = ['yarn install --frozen-lockfile'];
204
+ else if (files.packageLock) out.install = ['npm ci'];
205
+ else out.install = ['npm install'];
206
+
207
+ const runner = files.pnpmLock ? 'pnpm' : files.yarnLock ? 'yarn' : 'npm';
208
+
209
+ if (typeof scripts.build === 'string' && scripts.build.trim()) out.build = [`${runner} run build`];
210
+
211
+ if (typeof scripts.start === 'string' && scripts.start.trim()) {
212
+ out.start = runner === 'npm' ? 'npm start' : `${runner} start`;
213
+ } else if (typeof pkg.main === 'string' && pkg.main.trim()) {
214
+ out.start = `node ${pkg.main.trim()}`;
215
+ }
216
+
217
+ return out;
218
+ }
219
+
220
+ /**
221
+ * Validates the per-app overrides set in the dashboard or the Hub.
222
+ *
223
+ * Same shape as a parsed ez.json (`install`, `build`, `start`, `port`,
224
+ * `healthPath`, `healthTimeout`, `pre`, `post`). An absent, null or empty
225
+ * field means "do not override", so a form with untouched inputs overrides
226
+ * nothing. `false` for install/build/pre/post switches that step off.
227
+ *
228
+ * @param {*} input
229
+ * @returns {{ ok: boolean, value: Object, errors: string[] }}
230
+ */
231
+ export function normalizeOverrides(input) {
232
+ const errors = [];
233
+ const value = {};
234
+ if (input === undefined || input === null) return { ok: true, value, errors };
235
+ if (!isPlainObject(input)) return { ok: false, value, errors: ['settings must be an object'] };
236
+
237
+ for (const field of ['install', 'build', 'pre', 'post']) {
238
+ const raw = input[field];
239
+ if (raw === undefined || raw === null || raw === '') continue;
240
+ const n = normalizeCommands(raw);
241
+ if (n.error) errors.push(`${field} ${n.error}`);
242
+ else if (n.commands !== null) value[field] = n.commands;
243
+ }
244
+
245
+ if (input.start !== undefined && input.start !== null && input.start !== '') {
246
+ const n = normalizeCommands(input.start);
247
+ if (n.error) errors.push(`start ${n.error}`);
248
+ else if (n.commands.length !== 1) errors.push('start must be a single command');
249
+ else value.start = n.commands[0];
250
+ }
251
+
252
+ if (input.port !== undefined && input.port !== null && input.port !== '') {
253
+ const port = normalizePort(input.port);
254
+ if (port === null) errors.push('port must be a whole number from 1 to 65535');
255
+ else value.port = port;
256
+ }
257
+
258
+ if (input.healthPath !== undefined && input.healthPath !== null && input.healthPath !== '') {
259
+ const p = normalizeHealthPath(input.healthPath);
260
+ if (p === null) errors.push('healthPath must start with "/" and contain no spaces');
261
+ else value.healthPath = p;
262
+ }
263
+
264
+ if (input.healthTimeout !== undefined && input.healthTimeout !== null && input.healthTimeout !== '') {
265
+ const t = Number(input.healthTimeout);
266
+ if (!Number.isInteger(t) || t < 1 || t > MAX_HEALTH_TIMEOUT_S) {
267
+ errors.push(`healthTimeout must be a whole number of seconds from 1 to ${MAX_HEALTH_TIMEOUT_S}`);
268
+ } else {
269
+ value.healthTimeout = t;
270
+ }
271
+ }
272
+
273
+ return { ok: errors.length === 0, value, errors };
274
+ }
275
+
276
+ /**
277
+ * Merges the three sources into the settings a deployment actually runs with.
278
+ *
279
+ * `sources` records where each value came from, so the UI can show "from
280
+ * ez.json" next to a command instead of leaving the operator to guess which
281
+ * of three places to edit.
282
+ *
283
+ * @param {Object} input
284
+ * @param {Object|null} [input.ez] Value from parseEzFile(), or null
285
+ * @param {Object|null} [input.pkg] Parsed package.json, or null
286
+ * @param {Object} [input.files] Lockfiles present, see defaultsFromPackageJson()
287
+ * @param {Object} [input.overrides] Value from normalizeOverrides()
288
+ * @returns {{
289
+ * ok: boolean, error: string|null,
290
+ * settings: { install: string[], build: string[], start: string|null, port: number|null,
291
+ * healthPath: string, healthTimeout: number, pre: string[], post: string[] },
292
+ * sources: Object<string, 'override'|'ez.json'|'package.json'|'default'>
293
+ * }}
294
+ */
295
+ export function resolveSettings({ ez = null, pkg = null, files = {}, overrides = {} } = {}) {
296
+ const defaults = defaultsFromPackageJson(pkg, files);
297
+ const layers = [
298
+ ['override', overrides ?? {}],
299
+ ['ez.json', ez ?? {}],
300
+ ['package.json', defaults],
301
+ ];
302
+
303
+ const sources = {};
304
+ const pick = (field, fallback) => {
305
+ for (const [name, layer] of layers) {
306
+ if (layer[field] !== undefined && layer[field] !== null) {
307
+ sources[field] = name;
308
+ return layer[field];
309
+ }
310
+ }
311
+ sources[field] = 'default';
312
+ return fallback;
313
+ };
314
+
315
+ const settings = {
316
+ install: pick('install', []),
317
+ build: pick('build', []),
318
+ start: pick('start', null),
319
+ port: pick('port', null),
320
+ healthPath: pick('healthPath', DEFAULT_HEALTH_PATH),
321
+ healthTimeout: pick('healthTimeout', DEFAULT_HEALTH_TIMEOUT_S),
322
+ pre: pick('pre', []),
323
+ post: pick('post', []),
324
+ };
325
+
326
+ if (!settings.start) {
327
+ return {
328
+ ok: false,
329
+ error:
330
+ 'Nothing to start. Add a "start" command to ez.json, set one on the app, ' +
331
+ 'or give package.json a "start" script or a "main" file.',
332
+ settings,
333
+ sources,
334
+ };
335
+ }
336
+
337
+ return { ok: true, error: null, settings, sources };
338
+ }
339
+
340
+ /**
341
+ * Splits a start command into what PM2 needs.
342
+ *
343
+ * `node <file> [args]` is run by PM2 directly, so PM2 watches the real process.
344
+ * Anything else — `npm start`, `python app.py`, `./server` — goes through the
345
+ * launcher (core/deploy/launcher.js), because PM2 cannot run a command line,
346
+ * and how to run one differs per platform.
347
+ *
348
+ * @param {string} start
349
+ * @returns {{ kind: 'node', script: string, args: string[] } | { kind: 'command', command: string }}
350
+ */
351
+ export function parseStartCommand(start) {
352
+ const cmd = String(start ?? '').trim();
353
+ // Only the simplest form is taken apart. Quotes, environment prefixes,
354
+ // `&&`, pipes or node flags all mean "this is a command line": run it as one.
355
+ const m = /^node\s+([A-Za-z0-9_@./\\-]+)((?:\s+[A-Za-z0-9_@./\\=:,-]+)*)\s*$/.exec(cmd);
356
+ if (m && !m[1].startsWith('-')) {
357
+ const args = m[2].trim() ? m[2].trim().split(/\s+/) : [];
358
+ return { kind: 'node', script: m[1], args };
359
+ }
360
+ return { kind: 'command', command: cmd };
361
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * core/deploy/github.js
3
+ *
4
+ * What a repository needs in order to deploy through Easy DevOps: the workflow
5
+ * file, the secrets it reads, and the URL it calls.
6
+ *
7
+ * Pure text generation — nothing here talks to GitHub. The dashboard shows the
8
+ * result as steps to follow. (Creating the secrets through GitHub's API needs
9
+ * libsodium sealed boxes, which Node's crypto does not provide; doing it would
10
+ * mean a new dependency, and that is a decision, not a detail.)
11
+ */
12
+
13
+ import { DEPLOY_HOOK_PATH } from '../nginx-conf-generator.js';
14
+
15
+ export const SECRET_URL = 'EZ_DEPLOY_URL';
16
+ export const SECRET_TOKEN = 'EZ_DEPLOY_TOKEN';
17
+
18
+ /** Where the workflow file belongs in the repository. */
19
+ export function workflowPath(appId) {
20
+ return `.github/workflows/ez-deploy-${appId}.yml`;
21
+ }
22
+
23
+ /**
24
+ * The public URL a CI job calls to deploy an app, or null when the hook is
25
+ * not reachable from outside yet.
26
+ *
27
+ * @param {string} appId
28
+ * @param {{ enabled: boolean, port: number, bind: string, domain: string|null }} hook
29
+ * @param {Array<Object>} domains Domain records, to tell whether the chosen one has SSL
30
+ * @returns {{ url: string|null, mode: 'domain'|'direct'|'none', secure: boolean, note: string }}
31
+ */
32
+ export function hookUrl(appId, hook, domains = []) {
33
+ if (!hook?.enabled) {
34
+ return { url: null, mode: 'none', secure: false, note: 'The deploy hook is switched off.' };
35
+ }
36
+
37
+ if (hook.domain) {
38
+ const record = domains.find((d) => d.name === hook.domain);
39
+ if (!record) {
40
+ return { url: null, mode: 'none', secure: false, note: `The domain ${hook.domain} no longer exists. Pick another one for the deploy hook.` };
41
+ }
42
+ if (record.enabled === false) {
43
+ return { url: null, mode: 'none', secure: false, note: `The domain ${hook.domain} is disabled, so the deploy hook cannot be reached through it.` };
44
+ }
45
+ const secure = Boolean(record.ssl?.enabled);
46
+ return {
47
+ url: `${secure ? 'https' : 'http'}://${hook.domain}${DEPLOY_HOOK_PATH}${appId}`,
48
+ mode: 'domain',
49
+ secure,
50
+ note: secure
51
+ ? `Reached through ${hook.domain} over HTTPS.`
52
+ : `Reached through ${hook.domain} over plain HTTP — the deploy token is sent unencrypted. Enable SSL on that domain.`,
53
+ };
54
+ }
55
+
56
+ if (hook.bind === '0.0.0.0') {
57
+ return {
58
+ url: `http://YOUR_SERVER_ADDRESS:${hook.port}${DEPLOY_HOOK_PATH}${appId}`,
59
+ mode: 'direct',
60
+ secure: false,
61
+ note:
62
+ `Listening directly on port ${hook.port}, over plain HTTP — the deploy token is sent unencrypted. ` +
63
+ 'Replace YOUR_SERVER_ADDRESS with the server\'s public address, open the port in the firewall, ' +
64
+ 'and prefer exposing the hook through a domain with SSL.',
65
+ };
66
+ }
67
+
68
+ return {
69
+ url: null,
70
+ mode: 'none',
71
+ secure: false,
72
+ note: 'The deploy hook only listens on this machine. Expose it through a domain, or let it listen on all interfaces.',
73
+ };
74
+ }
75
+
76
+ /** Path of the Hub's CI endpoint, relative to the Hub's origin. Must match hub_backend/src/routes/api/v1/hooks.ts. */
77
+ export const HUB_HOOK_PATH = '/api/v1/hooks/deploy/';
78
+
79
+ /**
80
+ * The URL a CI job calls to deploy through the Hub, or null when this server
81
+ * is not paired.
82
+ *
83
+ * Same request, same token and same answers as the server's own deploy hook —
84
+ * the Hub forwards it down the agent connection the server already holds
85
+ * open, and the SERVER verifies the token. So the workflow file is identical
86
+ * either way; only the value of the EZ_DEPLOY_URL secret differs, and the
87
+ * server needs no inbound port at all.
88
+ *
89
+ * @param {string} appId
90
+ * @param {{ origin: string, serverId: string }|null} hubLink
91
+ * @param {boolean} allowed Whether the server grants `deploy.ci`
92
+ */
93
+ export function hubHookUrl(appId, hubLink, allowed) {
94
+ if (!hubLink?.origin || !hubLink?.serverId) {
95
+ return { url: null, secure: false, note: 'This server is not paired with a Hub.' };
96
+ }
97
+ const url = `${hubLink.origin}${HUB_HOOK_PATH}${hubLink.serverId}/${appId}`;
98
+ const secure = /^https:\/\//i.test(hubLink.origin);
99
+ if (!allowed) {
100
+ return {
101
+ url,
102
+ secure,
103
+ note: 'Turn on “Deploy from CI through the Hub” in Settings → Hub first; until then this server refuses the request.',
104
+ };
105
+ }
106
+ return {
107
+ url,
108
+ secure,
109
+ note: secure
110
+ ? 'Goes through the Hub over HTTPS. This server needs no inbound port.'
111
+ : 'Goes through the Hub over plain HTTP — the deploy token is sent unencrypted.',
112
+ };
113
+ }
114
+
115
+ /**
116
+ * The GitHub Actions workflow for an app.
117
+ *
118
+ * It triggers the deployment and then WAITS for the outcome, so a failed
119
+ * deployment is a red check on the commit rather than something discovered
120
+ * later. No third-party actions: only curl and the shell that every runner
121
+ * has, so there is nothing to pin and nothing to audit.
122
+ *
123
+ * @param {{ appId: string, branch: string }} opts
124
+ * @returns {string} YAML
125
+ */
126
+ export function buildWorkflow({ appId, branch }) {
127
+ return `# Deploys "${appId}" with Easy DevOps on every push to ${branch}.
128
+ # Generated by Easy DevOps — safe to edit.
129
+ #
130
+ # Needs two repository secrets (Settings → Secrets and variables → Actions):
131
+ # ${SECRET_URL} the deploy hook URL for this app
132
+ # ${SECRET_TOKEN} the deploy token for this app
133
+ name: Deploy ${appId}
134
+
135
+ on:
136
+ push:
137
+ branches: [${JSON.stringify(branch)}]
138
+ workflow_dispatch:
139
+
140
+ # One deployment of this app at a time; a newer push waits for the running one.
141
+ concurrency:
142
+ group: ez-deploy-${appId}
143
+ cancel-in-progress: false
144
+
145
+ jobs:
146
+ deploy:
147
+ runs-on: ubuntu-latest
148
+ timeout-minutes: 30
149
+ steps:
150
+ - name: Deploy
151
+ env:
152
+ ${SECRET_URL}: \${{ secrets.${SECRET_URL} }}
153
+ ${SECRET_TOKEN}: \${{ secrets.${SECRET_TOKEN} }}
154
+ run: |
155
+ set -euo pipefail
156
+
157
+ if [ -z "\${${SECRET_URL}:-}" ] || [ -z "\${${SECRET_TOKEN}:-}" ]; then
158
+ echo "::error::Set the ${SECRET_URL} and ${SECRET_TOKEN} repository secrets."
159
+ exit 1
160
+ fi
161
+
162
+ echo "Requesting deployment of $GITHUB_SHA"
163
+ response=$(curl --silent --show-error --fail-with-body --max-time 30 \\
164
+ -X POST "$${SECRET_URL}" \\
165
+ -H "Authorization: Bearer $${SECRET_TOKEN}" \\
166
+ -H "Content-Type: application/json" \\
167
+ -d "{\\"ref\\":\\"$GITHUB_SHA\\"}") || { echo "::error::The deploy hook refused the request: $response"; exit 1; }
168
+
169
+ run_id=$(printf '%s' "$response" | sed -n 's/.*"runId":"\\([^"]*\\)".*/\\1/p')
170
+ if [ -z "$run_id" ]; then
171
+ echo "::error::Unexpected answer from the deploy hook: $response"
172
+ exit 1
173
+ fi
174
+ echo "Deployment $run_id started"
175
+
176
+ # Wait for the server to finish: up to 25 minutes, checking every 10s.
177
+ for attempt in $(seq 1 150); do
178
+ sleep 10
179
+ state=$(curl --silent --show-error --max-time 20 \\
180
+ -H "Authorization: Bearer $${SECRET_TOKEN}" \\
181
+ "$${SECRET_URL}/runs/$run_id") || { echo "Could not read the status yet, retrying"; continue; }
182
+
183
+ status=$(printf '%s' "$state" | sed -n 's/.*"status":"\\([^"]*\\)".*/\\1/p')
184
+ step=$(printf '%s' "$state" | sed -n 's/.*"step":"\\([^"]*\\)".*/\\1/p')
185
+
186
+ case "$status" in
187
+ running) echo " ... $step" ;;
188
+ success) echo "Deployed."; exit 0 ;;
189
+ rolled_back)
190
+ echo "::error::The deployment failed and the previous release was restored. $state"
191
+ exit 1 ;;
192
+ failed)
193
+ echo "::error::The deployment failed. $state"
194
+ exit 1 ;;
195
+ *) echo " unexpected status: $state" ;;
196
+ esac
197
+ done
198
+
199
+ echo "::error::Timed out waiting for the deployment to finish."
200
+ exit 1
201
+ `;
202
+ }
203
+
204
+ /**
205
+ * Everything the "Connect to GitHub" steps need, in one object.
206
+ *
207
+ * @param {Object} app An app as returned by dashboardApp()
208
+ * @param {Object} hook hookSettings()
209
+ * @param {Array<Object>} domains
210
+ * @param {{ link: { origin: string, serverId: string }|null, ciAllowed: boolean }} [hub]
211
+ * @returns {Object}
212
+ */
213
+ export function describeGithubSetup(app, hook, domains = [], hub = { link: null, ciAllowed: false }) {
214
+ const target = hookUrl(app.id, hook, domains);
215
+ const viaHub = hubHookUrl(app.id, hub?.link ?? null, Boolean(hub?.ciAllowed));
216
+ return {
217
+ // Both ways of reaching this server, for the user to choose between.
218
+ // `hookUrl` below stays the direct one, as in contract 2.4.0.
219
+ targets: [
220
+ { id: 'hook', label: 'This server’s deploy hook', url: target.url, secure: target.secure, note: target.note },
221
+ { id: 'hub', label: 'Through the Hub', url: viaHub.url, secure: viaHub.secure, note: viaHub.note, ready: Boolean(viaHub.url && hub?.ciAllowed) },
222
+ ],
223
+ hookUrl: target.url,
224
+ hookMode: target.mode,
225
+ hookSecure: target.secure,
226
+ hookNote: target.note,
227
+ hasToken: Boolean(app.hook?.hasToken),
228
+ tokenHint: app.hook?.tokenHint ?? null,
229
+ workflowPath: workflowPath(app.id),
230
+ workflow: buildWorkflow({ appId: app.id, branch: app.branch }),
231
+ secrets: [
232
+ { name: SECRET_URL, value: target.url },
233
+ // Never readable back: only its hash is stored. The UI shows it once,
234
+ // at the moment it is generated.
235
+ { name: SECRET_TOKEN, value: null },
236
+ ],
237
+ deployKey: app.authType === 'deployKey' ? (app.deployKey ?? null) : null,
238
+ };
239
+ }