easy-devops 1.3.6 → 1.4.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 (78) 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/install.bat +14 -7
  7. package/package.json +2 -2
  8. package/src/cli/index.js +8 -0
  9. package/src/cli/managers/domain-manager.js +37 -6
  10. package/src/cli/managers/nginx-manager.js +14 -5
  11. package/src/cli/managers/node-manager.js +19 -13
  12. package/src/cli/managers/ssl-manager.js +89 -26
  13. package/src/cli/menu.js +8 -2
  14. package/src/cli/menus/cleanup.js +4 -2
  15. package/src/cli/menus/dashboard.js +22 -15
  16. package/src/cli/menus/hub.js +402 -0
  17. package/src/cli/menus/runtime.js +12 -0
  18. package/src/cli/menus/service.js +80 -13
  19. package/src/cli/menus/settings.js +46 -12
  20. package/src/cli/menus/uninstall.js +13 -5
  21. package/src/cli/menus/update.js +24 -14
  22. package/src/cli/ui/page.js +123 -0
  23. package/src/core/cert-operations.js +34 -4
  24. package/src/core/cert-reader.js +67 -22
  25. package/src/core/cert-renewal.js +65 -9
  26. package/src/core/cert-suggest.js +120 -0
  27. package/src/core/cleanup.js +221 -1
  28. package/src/core/cloudflare-ips.js +161 -0
  29. package/src/core/daemon/ipc.js +1 -1
  30. package/src/core/daemon/lock.js +296 -9
  31. package/src/core/daemon/run.js +12 -0
  32. package/src/core/daemon/stateFile.js +128 -0
  33. package/src/core/dashboardProcess.js +134 -6
  34. package/src/core/db.js +26 -1
  35. package/src/core/deploy/apps.js +36 -62
  36. package/src/core/deploy/deployKey.js +331 -0
  37. package/src/core/deploy/domainLink.js +280 -23
  38. package/src/core/deploy/engine.js +382 -63
  39. package/src/core/deploy/ezfile.js +496 -29
  40. package/src/core/deploy/githubApi.js +100 -13
  41. package/src/core/deploy/hubCommands.js +158 -18
  42. package/src/core/deploy/status.js +28 -1
  43. package/src/core/domains-db.js +1 -0
  44. package/src/core/hub/agent.js +238 -32
  45. package/src/core/hub/deployProgress.js +411 -0
  46. package/src/core/hubConnect.js +205 -0
  47. package/src/core/hubPermissions.js +48 -10
  48. package/src/core/jobs/bus.js +1 -1
  49. package/src/core/jobs/owner.js +268 -6
  50. package/src/core/nginx-conf-generator.js +124 -19
  51. package/src/core/notifications/claim.js +26 -3
  52. package/src/core/permissions.js +277 -59
  53. package/src/core/platform.js +73 -2
  54. package/src/core/runner.js +96 -40
  55. package/src/core/service/dataDir.js +34 -9
  56. package/src/core/service/index.js +203 -24
  57. package/src/core/service/runtime.js +40 -3
  58. package/src/core/service/windowsService.js +452 -107
  59. package/src/core/service/winsw.js +44 -3
  60. package/src/core/ssl/preflight.js +548 -0
  61. package/src/core/ssl/progress.js +196 -0
  62. package/src/core/ssl-issuer.js +502 -148
  63. package/src/core/validators.js +24 -0
  64. package/src/dashboard/controllers/authController.js +12 -5
  65. package/src/dashboard/controllers/deploymentsController.js +76 -11
  66. package/src/dashboard/controllers/domainsController.js +35 -1
  67. package/src/dashboard/controllers/hubController.js +4 -3
  68. package/src/dashboard/controllers/settingsController.js +73 -68
  69. package/src/dashboard/controllers/sslController.js +135 -15
  70. package/src/dashboard/public/js/app.js +42 -7
  71. package/src/dashboard/routes/deployments.js +2 -0
  72. package/src/dashboard/routes/domains.js +1 -0
  73. package/src/dashboard/server.js +42 -7
  74. package/src/dashboard/socketManager.js +19 -25
  75. package/src/dashboard/views/partials/settings-panel.ejs +29 -10
  76. package/dist/ui/assets/index-BUpPxWmp.css +0 -1
  77. package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
  78. package/dist/ui/assets/socket-4tfdap-e.js +0 -65
package/src/core/db.js CHANGED
@@ -12,6 +12,11 @@ const DATA_DIR = getDataDir();
12
12
 
13
13
  const DB_PATH = path.join(DATA_DIR, 'easy-devops.sqlite');
14
14
 
15
+ // The file the open connection uses. It equals DB_PATH for the life of almost
16
+ // every process; only reopenDb() moves it, after the Windows Server-mode
17
+ // migration has changed what getDataDir() answers.
18
+ let dbPath = DB_PATH;
19
+
15
20
  // ─── One-time migration from old package-relative location ───────────────────
16
21
  const OLD_DATA_DIR = path.join(__dirname, '..', '..', 'data');
17
22
  const OLD_DB_PATH = path.join(OLD_DATA_DIR, 'easy-devops.sqlite');
@@ -70,7 +75,7 @@ let db;
70
75
  * per call site without every future caller having to remember.
71
76
  */
72
77
  function createDbConnection() {
73
- return new GoodDB(new SQLiteDriver({ path: DB_PATH }), {
78
+ return new GoodDB(new SQLiteDriver({ path: dbPath }), {
74
79
  nested: "..",
75
80
  nestedIsEnabled: true,
76
81
  cache: {
@@ -117,3 +122,23 @@ export function initDb() {
117
122
  db = createDbConnection();
118
123
  }
119
124
  }
125
+
126
+ /**
127
+ * Closes the connection and opens the database in the CURRENT data directory.
128
+ *
129
+ * For the one place where the data directory changes within a process: the
130
+ * Windows Server-mode switch during `ezz service install`. Without it, the
131
+ * installing process kept writing to the per-user database it opened at
132
+ * startup — a file every later process ignores — and Windows refused to
133
+ * rename that directory to its backup name because this handle held it open.
134
+ *
135
+ * @returns {string} The database file now in use
136
+ */
137
+ export function reopenDb() {
138
+ closeDb();
139
+ const dir = getDataDir();
140
+ fs.mkdirSync(dir, { recursive: true });
141
+ dbPath = path.join(dir, 'easy-devops.sqlite');
142
+ db = createDbConnection();
143
+ return dbPath;
144
+ }
@@ -20,8 +20,9 @@ import crypto from 'crypto';
20
20
  import fs from 'fs';
21
21
 
22
22
  import { dbGet, dbSet } from '../db.js';
23
- import { normalizeOverrides } from './ezfile.js';
23
+ import { normalizeOverrides, settingsWarnings } from './ezfile.js';
24
24
  import path from 'path';
25
+ import { describeDeployKey } from './deployKey.js';
25
26
  import { appPaths, deployRoot, ensureAppDirs, removeAppFiles } from './store.js';
26
27
  import { EZ_APP_NAMES } from '../runner.js';
27
28
 
@@ -172,10 +173,11 @@ export function getApp(id) {
172
173
  * value, and the token is kept unless a new one is supplied — so the UI never
173
174
  * has to round-trip a secret just to change the branch.
174
175
  *
175
- * @returns {{ ok: boolean, value: Object|null, errors: string[] }}
176
+ * @returns {{ ok: boolean, value: Object|null, errors: string[], warnings: string[] }}
176
177
  */
177
178
  export function normalizeAppInput(input, existing = null) {
178
179
  const errors = [];
180
+ const warnings = [];
179
181
  const src = input && typeof input === 'object' ? input : {};
180
182
  const has = (k) => src[k] !== undefined;
181
183
 
@@ -206,8 +208,12 @@ export function normalizeAppInput(input, existing = null) {
206
208
  errors.push('A deploy key needs an SSH repository URL (git@github.com:owner/repo.git).');
207
209
  }
208
210
 
209
- const overrides = has('settings') ? normalizeOverrides(src.settings) : { ok: true, value: existing?.settings ?? {}, errors: [] };
211
+ const overrides = has('settings') ? normalizeOverrides(src.settings) : { ok: true, value: existing?.settings ?? {}, errors: [], warnings: [] };
210
212
  for (const e of overrides.errors) errors.push(e);
213
+ for (const w of overrides.warnings ?? []) warnings.push(w);
214
+ for (const w of settingsWarnings(overrides.value)) {
215
+ if (!warnings.includes(w)) warnings.push(w);
216
+ }
211
217
 
212
218
  const env = has('env') ? normalizeEnv(src.env) : { ok: true, value: existing?.env ?? {}, error: null };
213
219
  if (env.error) errors.push(env.error);
@@ -227,11 +233,12 @@ export function normalizeAppInput(input, existing = null) {
227
233
  }
228
234
  }
229
235
 
230
- if (errors.length > 0) return { ok: false, value: null, errors };
236
+ if (errors.length > 0) return { ok: false, value: null, errors, warnings };
231
237
 
232
238
  return {
233
239
  ok: true,
234
240
  errors,
241
+ warnings,
235
242
  value: {
236
243
  repoUrl,
237
244
  branch,
@@ -241,6 +248,8 @@ export function normalizeAppInput(input, existing = null) {
241
248
  // need the secret entered again. Only used when the type says so.
242
249
  token,
243
250
  publicKey: existing?.auth?.publicKey ?? null,
251
+ keyFingerprint: existing?.auth?.keyFingerprint ?? null,
252
+ keyCreatedAt: existing?.auth?.keyCreatedAt ?? null,
244
253
  },
245
254
  settings: overrides.value,
246
255
  env: env.value,
@@ -264,7 +273,7 @@ export function createApp(input) {
264
273
  if (apps.some((a) => a.id === id)) return { ok: false, errors: [`An app named "${id}" already exists.`], status: 409 };
265
274
 
266
275
  const normalized = normalizeAppInput(input);
267
- if (!normalized.ok) return { ok: false, errors: normalized.errors, status: 400 };
276
+ if (!normalized.ok) return { ok: false, errors: normalized.errors, warnings: normalized.warnings, status: 400 };
268
277
 
269
278
  const now = new Date().toISOString();
270
279
  const app = {
@@ -288,7 +297,7 @@ export function createApp(input) {
288
297
  saveApps(apps);
289
298
  return { ok: false, errors: [`Could not create ${app.dir}: ${err.message}`], status: 500 };
290
299
  }
291
- return { ok: true, app };
300
+ return { ok: true, app, warnings: normalized.warnings };
292
301
  }
293
302
 
294
303
  /**
@@ -301,12 +310,12 @@ export function updateApp(id, input) {
301
310
  if (index === -1) return { ok: false, errors: [`No app named "${id}".`], status: 404 };
302
311
 
303
312
  const normalized = normalizeAppInput(input, apps[index]);
304
- if (!normalized.ok) return { ok: false, errors: normalized.errors, status: 400 };
313
+ if (!normalized.ok) return { ok: false, errors: normalized.errors, warnings: normalized.warnings, status: 400 };
305
314
 
306
315
  const app = { ...apps[index], ...normalized.value, updatedAt: new Date().toISOString() };
307
316
  apps[index] = app;
308
317
  saveApps(apps);
309
- return { ok: true, app };
318
+ return { ok: true, app, warnings: normalized.warnings };
310
319
  }
311
320
 
312
321
  /** Records a new folder for an app after it has been moved. */
@@ -319,6 +328,18 @@ export function setAppDomain(id, domain) {
319
328
  return patchApp(id, { domain: domain ?? null });
320
329
  }
321
330
 
331
+ /**
332
+ * Records the PUBLIC half of a freshly written deploy key. The private key is
333
+ * never stored in the registry; core/deploy/deployKey.js writes it to disk.
334
+ */
335
+ export function setDeployKeyRecord(id, { publicKey, fingerprint, createdAt }) {
336
+ const app = getApp(id);
337
+ if (!app) return null;
338
+ return patchApp(id, {
339
+ auth: { ...(app.auth ?? {}), publicKey, keyFingerprint: fingerprint, keyCreatedAt: createdAt },
340
+ });
341
+ }
342
+
322
343
  /** Low-level patch for fields this module owns (hook token, deploy key, folder, domain). */
323
344
  function patchApp(id, patch) {
324
345
  const apps = listApps();
@@ -391,59 +412,6 @@ export function verifyHookToken(app, presented) {
391
412
 
392
413
  // ─── The deploy key ───────────────────────────────────────────────────────────
393
414
 
394
- /** SSH wire encoding of a length-prefixed byte string. */
395
- function sshString(buf) {
396
- const len = Buffer.alloc(4);
397
- len.writeUInt32BE(buf.length);
398
- return Buffer.concat([len, buf]);
399
- }
400
-
401
- /** SSH wire encoding of a positive big integer (a leading zero if the top bit is set). */
402
- function sshMpint(buf) {
403
- let b = buf;
404
- while (b.length > 1 && b[0] === 0) b = b.subarray(1);
405
- if (b[0] & 0x80) b = Buffer.concat([Buffer.from([0]), b]);
406
- return sshString(b);
407
- }
408
-
409
- /**
410
- * Generates an RSA key pair for an app and stores the private half on disk.
411
- *
412
- * Generated in-process rather than with `ssh-keygen`, so it does not depend on
413
- * which OpenSSH tools a machine has. RSA-4096 with a PKCS#1 PEM private key is
414
- * the one format every OpenSSH client reads, on both platforms.
415
- *
416
- * The public key is returned and stored; the private key is written with
417
- * owner-only permissions and never returned by any API.
418
- *
419
- * @returns {{ publicKey: string } | null} null when the app does not exist
420
- */
421
- export function generateDeployKey(id) {
422
- if (!getApp(id)) return null;
423
-
424
- const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
425
- modulusLength: 4096,
426
- publicKeyEncoding: { type: 'spki', format: 'pem' },
427
- privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
428
- });
429
-
430
- const jwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
431
- const blob = Buffer.concat([
432
- sshString(Buffer.from('ssh-rsa')),
433
- sshMpint(Buffer.from(jwk.e, 'base64url')),
434
- sshMpint(Buffer.from(jwk.n, 'base64url')),
435
- ]);
436
- const sshPublic = `ssh-rsa ${blob.toString('base64')} easy-devops-deploy-${id}`;
437
-
438
- const p = ensureAppDirs(id);
439
- fs.writeFileSync(p.deployKey, privateKey, { mode: 0o600 });
440
- try { fs.chmodSync(p.deployKey, 0o600); } catch { /* not meaningful on Windows */ }
441
-
442
- const app = getApp(id);
443
- patchApp(id, { auth: { ...(app.auth ?? {}), publicKey: sshPublic } });
444
- return { publicKey: sshPublic };
445
- }
446
-
447
415
  /** Path of an app's private deploy key, or null when it has none on disk. */
448
416
  export function deployKeyPath(id) {
449
417
  const file = appPaths(id).deployKey;
@@ -460,6 +428,7 @@ export function deployKeyPath(id) {
460
428
  export function dashboardApp(app) {
461
429
  if (!app) return null;
462
430
  const paths = appPaths(app.id);
431
+ const key = describeDeployKey(app);
463
432
  let hasSharedData = false;
464
433
  try { hasSharedData = fs.readdirSync(paths.shared).length > 0; } catch { /* nothing persistent */ }
465
434
  return {
@@ -469,8 +438,13 @@ export function dashboardApp(app) {
469
438
  branch: app.branch,
470
439
  authType: app.auth?.type ?? AUTH_TYPES.NONE,
471
440
  hasToken: Boolean(app.auth?.token),
472
- deployKey: app.auth?.publicKey ?? null,
441
+ deployKey: key.publicKey,
442
+ deployKeyFingerprint: key.fingerprint,
443
+ deployKeyCreatedAt: key.createdAt,
444
+ deployKeyOnDisk: key.onDisk,
473
445
  settings: app.settings ?? {},
446
+ /** Advisory notes the UI shows beside the settings (cluster mode's stateless warning). */
447
+ warnings: settingsWarnings(app.settings ?? {}),
474
448
  env: app.env ?? {},
475
449
  keepReleases: app.keepReleases ?? DEFAULT_KEEP_RELEASES,
476
450
  autoRollback: app.autoRollback !== false,
@@ -0,0 +1,331 @@
1
+ /**
2
+ * core/deploy/deployKey.js
3
+ *
4
+ * The SSH deploy key an app fetches its repository with: generating it,
5
+ * replacing it, and proving it works.
6
+ *
7
+ * Three rules hold everywhere in this file:
8
+ *
9
+ * 1. The private key goes to exactly one place, `<app dir>/id_deploy`, with
10
+ * owner-only permissions. No function returns it, logs it or puts it in
11
+ * the registry; callers only ever see the public key and its fingerprint.
12
+ * 2. GitHub's host keys are PINNED. The connection test (and every fetch from
13
+ * github.com, see sshCommand()) checks the server against the keys GitHub
14
+ * publishes, with StrictHostKeyChecking=yes. Never accept-new: trusting
15
+ * whatever answers first is exactly when an interception would succeed.
16
+ * 3. Nothing here prompts. ssh runs with BatchMode, git with
17
+ * GIT_TERMINAL_PROMPT=0, so a missing key is an error, never a hang.
18
+ *
19
+ * The key is ed25519, written in the openssh-key-v1 format by hand: Node can
20
+ * generate the pair, but only exports PKCS#8 for ed25519, which OpenSSH builds
21
+ * do not all read. Generating in-process also means no dependency on
22
+ * `ssh-keygen` being installed.
23
+ */
24
+
25
+ import crypto from 'crypto';
26
+ import fs from 'fs';
27
+ import path from 'path';
28
+
29
+ import { run as shellRun } from '../shell.js';
30
+ import { getApp, isSshUrl, setDeployKeyRecord } from './apps.js';
31
+ import { appPaths, ensureAppDirs } from './store.js';
32
+
33
+ // ─── GitHub's host keys ───────────────────────────────────────────────────────
34
+
35
+ /**
36
+ * GitHub's SSH host keys, as published at https://api.github.com/meta
37
+ * (`ssh_keys`) and in GitHub's docs, "GitHub's SSH key fingerprints".
38
+ * Checked 2026-11-18. If GitHub rotates a key, update it here; the e2e suite
39
+ * checks each key against the fingerprint GitHub publishes for it.
40
+ */
41
+ export const GITHUB_HOST_KEYS = Object.freeze([
42
+ 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl',
43
+ 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=',
44
+ 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=',
45
+ ]);
46
+
47
+ /** The fingerprints GitHub publishes for the keys above (`ssh_key_fingerprints`). */
48
+ export const GITHUB_HOST_FINGERPRINTS = Object.freeze({
49
+ 'ssh-ed25519': 'SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU',
50
+ 'ecdsa-sha2-nistp256': 'SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM',
51
+ 'ssh-rsa': 'SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s',
52
+ });
53
+
54
+ /** The known_hosts lines for github.com, built from GITHUB_HOST_KEYS. */
55
+ export function githubKnownHosts() {
56
+ return GITHUB_HOST_KEYS.map((key) => `github.com ${key}`).join('\n') + '\n';
57
+ }
58
+
59
+ // ─── Encoding ─────────────────────────────────────────────────────────────────
60
+
61
+ /** SSH wire encoding of a length-prefixed byte string. */
62
+ function sshString(buf) {
63
+ const len = Buffer.alloc(4);
64
+ len.writeUInt32BE(buf.length);
65
+ return Buffer.concat([len, buf]);
66
+ }
67
+
68
+ function uint32(n) {
69
+ const b = Buffer.alloc(4);
70
+ b.writeUInt32BE(n >>> 0);
71
+ return b;
72
+ }
73
+
74
+ /**
75
+ * The OpenSSH fingerprint of a public key line or blob: `SHA256:` and the
76
+ * unpadded base64 of the blob's SHA-256, as `ssh-keygen -lf` prints it.
77
+ *
78
+ * @param {string|Buffer} key "type base64 [comment]" or the raw blob
79
+ */
80
+ export function fingerprintOf(key) {
81
+ const blob = Buffer.isBuffer(key) ? key : Buffer.from(String(key).trim().split(/\s+/)[1] ?? '', 'base64');
82
+ return `SHA256:${crypto.createHash('sha256').update(blob).digest('base64').replace(/=+$/, '')}`;
83
+ }
84
+
85
+ /**
86
+ * A new ed25519 pair: the public key line and the openssh-key-v1 private key.
87
+ * Exported for the test suite, which checks the format; nothing else should
88
+ * need the private half outside this module.
89
+ *
90
+ * @param {string} comment
91
+ * @returns {{ publicKey: string, fingerprint: string, privateKey: Buffer }}
92
+ */
93
+ export function createEd25519Pair(comment) {
94
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
95
+ const pub = Buffer.from(publicKey.export({ format: 'jwk' }).x, 'base64url');
96
+ const seed = Buffer.from(privateKey.export({ format: 'jwk' }).d, 'base64url');
97
+
98
+ const type = Buffer.from('ssh-ed25519');
99
+ const pubBlob = Buffer.concat([sshString(type), sshString(pub)]);
100
+
101
+ // The private section: two equal check integers, the key, the comment, then
102
+ // padding 1, 2, 3, … up to a multiple of the cipher block size (8 for none).
103
+ const check = crypto.randomBytes(4);
104
+ let section = Buffer.concat([
105
+ check, check,
106
+ sshString(type),
107
+ sshString(pub),
108
+ sshString(Buffer.concat([seed, pub])),
109
+ sshString(Buffer.from(comment)),
110
+ ]);
111
+ const pad = (8 - (section.length % 8)) % 8;
112
+ section = Buffer.concat([section, Buffer.from(Array.from({ length: pad }, (_, i) => i + 1))]);
113
+
114
+ const body = Buffer.concat([
115
+ Buffer.from('openssh-key-v1\0'),
116
+ sshString(Buffer.from('none')), // cipher
117
+ sshString(Buffer.from('none')), // kdf
118
+ sshString(Buffer.alloc(0)), // kdf options
119
+ uint32(1), // one key
120
+ sshString(pubBlob),
121
+ sshString(section),
122
+ ]);
123
+ const b64 = body.toString('base64').replace(/.{1,70}/g, '$&\n');
124
+ const pem = Buffer.from(`-----BEGIN OPENSSH PRIVATE KEY-----\n${b64}-----END OPENSSH PRIVATE KEY-----\n`);
125
+
126
+ seed.fill(0);
127
+ section.fill(0);
128
+ body.fill(0);
129
+
130
+ return {
131
+ publicKey: `ssh-ed25519 ${pubBlob.toString('base64')} ${comment}`,
132
+ fingerprint: fingerprintOf(pubBlob),
133
+ privateKey: pem,
134
+ };
135
+ }
136
+
137
+ // ─── Generating and replacing ─────────────────────────────────────────────────
138
+
139
+ /**
140
+ * Generates the app's deploy key, replacing any previous one.
141
+ *
142
+ * The private key is written to a temporary file with mode 600 and renamed
143
+ * over `id_deploy`, so a deployment reading the key never sees half a file.
144
+ * Replacing it is what invalidates the old key on this server: the old private
145
+ * half is gone. GitHub still lists the old PUBLIC key until someone removes it,
146
+ * which is why the previous fingerprint is returned — the UI says so.
147
+ *
148
+ * @param {string} id
149
+ * @param {{ now?: () => Date }} [opts]
150
+ * @returns {{ publicKey: string, fingerprint: string, createdAt: string,
151
+ * previousFingerprint: string|null } | null} null when the app does not exist
152
+ */
153
+ export function generateDeployKey(id, { now = () => new Date() } = {}) {
154
+ const app = getApp(id);
155
+ if (!app) return null;
156
+
157
+ const previousFingerprint = app.auth?.keyFingerprint
158
+ ?? (app.auth?.publicKey ? fingerprintOf(app.auth.publicKey) : null);
159
+
160
+ const pair = createEd25519Pair(`easy-devops-deploy-${id}`);
161
+ const p = ensureAppDirs(id);
162
+ const tmp = `${p.deployKey}.${process.pid}.tmp`;
163
+ try {
164
+ fs.rmSync(tmp, { force: true });
165
+ fs.writeFileSync(tmp, pair.privateKey, { mode: 0o600, flag: 'wx' });
166
+ try { fs.chmodSync(tmp, 0o600); } catch { /* no POSIX modes on Windows; the data dir's ACL applies */ }
167
+ fs.renameSync(tmp, p.deployKey);
168
+ } catch (err) {
169
+ fs.rmSync(tmp, { force: true });
170
+ throw new Error(`Could not write the deploy key in ${p.root}: ${err.code ?? err.message}. Check that this folder is writable by the user Easy DevOps runs as.`);
171
+ } finally {
172
+ pair.privateKey.fill(0);
173
+ }
174
+
175
+ const createdAt = now().toISOString();
176
+ setDeployKeyRecord(id, { publicKey: pair.publicKey, fingerprint: pair.fingerprint, createdAt });
177
+ return { publicKey: pair.publicKey, fingerprint: pair.fingerprint, createdAt, previousFingerprint };
178
+ }
179
+
180
+ /**
181
+ * What may be shown about an app's key: never the private half.
182
+ * @returns {{ publicKey: string|null, fingerprint: string|null, createdAt: string|null, onDisk: boolean }}
183
+ */
184
+ export function describeDeployKey(app) {
185
+ const publicKey = app?.auth?.publicKey ?? null;
186
+ let onDisk = false;
187
+ try { onDisk = Boolean(app) && fs.statSync(appPaths(app.id).deployKey).isFile(); } catch { /* none */ }
188
+ return {
189
+ publicKey,
190
+ fingerprint: app?.auth?.keyFingerprint ?? (publicKey ? fingerprintOf(publicKey) : null),
191
+ createdAt: app?.auth?.keyCreatedAt ?? null,
192
+ onDisk,
193
+ };
194
+ }
195
+
196
+ // ─── Using the key ────────────────────────────────────────────────────────────
197
+
198
+ /** github.com over SSH, in either URL form. Strict on purpose: the result is put in a command line. */
199
+ const GITHUB_SSH_URL =
200
+ /^(?:ssh:\/\/[A-Za-z0-9._-]+@github\.com(?::22)?\/[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+|[A-Za-z0-9._-]+@github\.com:[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)$/i;
201
+
202
+ /**
203
+ * How long the connection test waits. Below the Hub's 15-second quick-command
204
+ * window, so a slow GitHub is reported as itself, not as an agent timeout.
205
+ */
206
+ const LS_REMOTE_TIMEOUT_MS = 12000;
207
+
208
+ /** True when the URL reaches github.com over SSH, so its host keys can be pinned. */
209
+ export function isGithubSshUrl(url) {
210
+ return GITHUB_SSH_URL.test(String(url ?? ''));
211
+ }
212
+
213
+ /** Characters that could end a quoted path inside GIT_SSH_COMMAND, which git runs through sh. */
214
+ const UNSAFE_PATH = /["`$\\\n\r]/;
215
+
216
+ /**
217
+ * The GIT_SSH_COMMAND for an app's key, or null when the key is missing.
218
+ *
219
+ * For github.com the host keys are pinned (StrictHostKeyChecking=yes against a
220
+ * known_hosts file this module writes). Other hosts keep the engine's earlier
221
+ * behaviour, accept-new, because there are no published keys to pin to; the
222
+ * connection test refuses them instead of pretending to verify them.
223
+ *
224
+ * @param {string} id
225
+ * @param {string} repoUrl
226
+ * @returns {string|null}
227
+ */
228
+ export function sshCommand(id, repoUrl) {
229
+ const p = appPaths(id);
230
+ if (!fs.existsSync(p.deployKey)) return null;
231
+ // Forward slashes: git runs this through its own sh, where a backslash in a
232
+ // Windows path would be read as an escape.
233
+ const keyArg = p.deployKey.replace(/\\/g, '/');
234
+ if (UNSAFE_PATH.test(keyArg)) {
235
+ throw new Error(`The app folder path contains a character ssh cannot be given safely: ${p.root}. Move the app to a plain path.`);
236
+ }
237
+ const base = `ssh -i "${keyArg}" -o IdentitiesOnly=yes -o BatchMode=yes`;
238
+ if (!isGithubSshUrl(repoUrl)) return `${base} -o StrictHostKeyChecking=accept-new`;
239
+
240
+ const knownHosts = path.join(p.root, 'known_hosts');
241
+ fs.writeFileSync(knownHosts, githubKnownHosts(), { mode: 0o644 });
242
+ const hostsArg = knownHosts.replace(/\\/g, '/');
243
+ return `${base} -o StrictHostKeyChecking=yes -o CheckHostIP=no -o UserKnownHostsFile="${hostsArg}"`;
244
+ }
245
+
246
+ /**
247
+ * Turns ssh/git's stderr into the reason and the next step, in that order.
248
+ * Unknown output falls through to its own last lines.
249
+ */
250
+ export function explainLsRemoteFailure(stderr, timedOut) {
251
+ const text = String(stderr ?? '');
252
+ if (timedOut) {
253
+ return 'GitHub did not answer within 12 seconds. Check that this server can reach github.com on port 22 (a firewall may block outgoing SSH), then test again.';
254
+ }
255
+ if (/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed|host key .* (?:mismatch|differs)/i.test(text)) {
256
+ return 'The server answering as github.com did not present GitHub\'s published host key, so the connection was refused. Something between this server and GitHub may be intercepting SSH; do not deploy until this is explained.';
257
+ }
258
+ if (/Permission denied \(publickey/i.test(text)) {
259
+ return 'GitHub rejected the key. Add the public key to the repository as a deploy key (Settings → Deploy keys → Add deploy key, read access is enough), then test again.';
260
+ }
261
+ if (/Repository not found|does not appear to be a git repository|Could not read from remote repository/i.test(text)) {
262
+ return 'GitHub accepted the connection but this key cannot read that repository. Check the repository URL, and that the key was added to THIS repository (deploy keys belong to one repository).';
263
+ }
264
+ if (/Could not resolve hostname|Name or service not known|Temporary failure in name resolution/i.test(text)) {
265
+ return 'This server could not resolve github.com. Check its DNS settings, then test again.';
266
+ }
267
+ if (/Connection (?:refused|timed out)|Network is unreachable|No route to host/i.test(text)) {
268
+ return 'This server could not open a connection to github.com on port 22. Allow outgoing SSH in the firewall, then test again.';
269
+ }
270
+ if (/(?:ssh|git)[^\n]*(?:not found|not recognized|No such file)/i.test(text)) {
271
+ return 'git or ssh is not installed or not on PATH for the user Easy DevOps runs as. Install Git (it includes ssh), then test again.';
272
+ }
273
+ const tail = text.trim().split(/\r?\n/).slice(-3).join(' ').slice(0, 400);
274
+ return tail ? `git ls-remote failed: ${tail}` : 'git ls-remote failed without saying why.';
275
+ }
276
+
277
+ /**
278
+ * "Test connection": `git ls-remote` with the app's key against its repository,
279
+ * with GitHub's host keys pinned.
280
+ *
281
+ * @param {string} id
282
+ * @param {{ run?: typeof shellRun }} [deps] Injected runner (testing only)
283
+ * @returns {Promise<{ ok: boolean, status: number, error: string|null,
284
+ * detail?: string, branchFound?: boolean|null, fingerprint?: string|null }>}
285
+ */
286
+ export async function testDeployKey(id, { run = shellRun } = {}) {
287
+ const app = getApp(id);
288
+ if (!app) return { ok: false, status: 404, error: `No app named "${id}".` };
289
+
290
+ if (!isSshUrl(app.repoUrl)) {
291
+ return { ok: false, status: 400, error: 'A deploy key needs an SSH repository URL (git@github.com:owner/repo.git).' };
292
+ }
293
+ if (!isGithubSshUrl(app.repoUrl)) {
294
+ return {
295
+ ok: false,
296
+ status: 400,
297
+ error: 'The connection test pins GitHub\'s published host keys, so it only tests github.com repositories. For another host, deploy once and read the fetch step.',
298
+ };
299
+ }
300
+
301
+ let sshCmd;
302
+ try {
303
+ sshCmd = sshCommand(id, app.repoUrl);
304
+ } catch (err) {
305
+ return { ok: false, status: 500, error: err.message };
306
+ }
307
+ if (!sshCmd) return { ok: false, status: 409, error: 'This app has no deploy key yet. Generate one first.' };
308
+
309
+ const result = await run(`git ls-remote --heads "${app.repoUrl}"`, {
310
+ timeout: LS_REMOTE_TIMEOUT_MS,
311
+ env: { GIT_TERMINAL_PROMPT: '0', GIT_SSH_COMMAND: sshCmd },
312
+ });
313
+ const fingerprint = describeDeployKey(app).fingerprint;
314
+
315
+ if (!result.success) {
316
+ return {
317
+ ok: false,
318
+ status: 200,
319
+ error: explainLsRemoteFailure(result.stderr, result.exitCode === null),
320
+ fingerprint,
321
+ };
322
+ }
323
+
324
+ const heads = String(result.stdout ?? '').split(/\r?\n/).filter((l) => /\trefs\/heads\//.test(l));
325
+ const branch = app.branch ? `refs/heads/${app.branch}` : null;
326
+ const branchFound = branch ? heads.some((l) => l.endsWith(`\t${branch}`)) : null;
327
+ const detail = branchFound === false
328
+ ? `Connected. The key can read the repository, but it has no branch "${app.branch}". Check the branch name before deploying.`
329
+ : `Connected. The key can read the repository${branch ? ` and its branch "${app.branch}"` : ''}.`;
330
+ return { ok: true, status: 200, error: null, detail, branchFound, fingerprint };
331
+ }