easy-devops 1.2.1 → 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.
- package/README.md +97 -6
- package/dist/ui/assets/index-B6zdwEnG.css +1 -0
- package/dist/ui/assets/index-Cy0oNmul.js +442 -0
- package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
- package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
- package/dist/ui/brand/apple-touch-icon.png +0 -0
- package/dist/ui/brand/favicon-16.png +0 -0
- package/dist/ui/brand/favicon-32.png +0 -0
- package/dist/ui/brand/favicon-light-16.png +0 -0
- package/dist/ui/brand/favicon-light-32.png +0 -0
- package/dist/ui/brand/favicon.ico +0 -0
- package/dist/ui/brand/icon-192.png +0 -0
- package/dist/ui/brand/icon-48.png +0 -0
- package/dist/ui/brand/icon-512.png +0 -0
- package/dist/ui/brand/icon-64-light.png +0 -0
- package/dist/ui/brand/icon-64.png +0 -0
- package/dist/ui/brand/logo-dark.png +0 -0
- package/dist/ui/brand/logo-light.png +0 -0
- package/dist/ui/brand/mark-dark.png +0 -0
- package/dist/ui/brand/mark-light.png +0 -0
- package/dist/ui/index.html +71 -0
- package/install.ps1 +188 -1
- package/install.sh +254 -29
- package/package.json +15 -4
- package/src/cli/dash.js +110 -0
- package/src/cli/index.js +237 -106
- package/src/cli/managers/domain-manager.js +60 -40
- package/src/cli/managers/ssl-manager.js +47 -330
- package/src/cli/menu.js +156 -0
- package/src/cli/menus/cleanup.js +205 -0
- package/src/cli/menus/dashboard.js +92 -1
- package/src/cli/menus/runtime.js +236 -0
- package/src/cli/menus/service.js +764 -0
- package/src/cli/menus/settings.js +176 -8
- package/src/cli/menus/uninstall.js +167 -0
- package/src/cli/menus/update.js +221 -65
- package/src/core/acme-challenge.js +273 -0
- package/src/core/cert-operations.js +189 -0
- package/src/{dashboard/lib → core}/cert-reader.js +2 -2
- package/src/core/cert-renewal.js +494 -0
- package/src/core/cleanup.js +600 -0
- package/src/core/config.js +169 -2
- package/src/core/daemon/ipc.js +292 -0
- package/src/core/daemon/lock.js +294 -0
- package/src/core/daemon/run.js +241 -0
- package/src/core/daemon/stopRequest.js +162 -0
- package/src/core/db.js +37 -8
- package/src/core/deploy/apps.js +491 -0
- package/src/core/deploy/domainLink.js +200 -0
- package/src/core/deploy/engine.js +973 -0
- package/src/core/deploy/ezfile.js +361 -0
- package/src/core/deploy/github.js +239 -0
- package/src/core/deploy/githubApi.js +261 -0
- package/src/core/deploy/hookServer.js +325 -0
- package/src/core/deploy/hubCommands.js +267 -0
- package/src/core/deploy/launcher.js +57 -0
- package/src/core/deploy/status.js +91 -0
- package/src/core/deploy/store.js +398 -0
- package/src/core/domainNotifier.js +94 -28
- package/src/core/domains-db.js +234 -0
- package/src/core/events.js +94 -2
- package/src/core/hub/agent.js +842 -0
- package/src/core/hubLink.js +306 -0
- package/src/core/hubPermissions.js +430 -0
- package/src/core/installSource.js +162 -0
- package/src/core/jobs/bus.js +120 -0
- package/src/core/jobs/index.js +371 -0
- package/src/core/jobs/monitors.js +368 -0
- package/src/core/jobs/owner.js +217 -0
- package/src/core/jobs/revisionWatcher.js +106 -0
- package/src/core/nginx-apply.js +213 -0
- package/src/core/nginx-conf-generator.js +253 -17
- package/src/{dashboard/lib → core}/nginx-service.js +18 -9
- package/src/core/notifications/claim.js +214 -0
- package/src/core/notifications/dispatch.js +154 -0
- package/src/core/notifier.js +31 -1
- package/src/core/passwords.js +172 -0
- package/src/core/permissions.js +8 -4
- package/src/core/platform.js +709 -2
- package/src/core/probeCache.js +258 -0
- package/src/core/purge.js +372 -0
- package/src/core/runner.js +488 -0
- package/src/core/service/acl.js +226 -0
- package/src/core/service/dataDir.js +345 -0
- package/src/core/service/index.js +1128 -0
- package/src/core/service/legacy.js +218 -0
- package/src/core/service/runtime.js +446 -0
- package/src/core/service/runtimeUpdate.js +800 -0
- package/src/core/service/systemd.js +458 -0
- package/src/core/service/windowsPersonal.js +530 -0
- package/src/core/service/windowsService.js +576 -0
- package/src/core/service/winsw.js +260 -0
- package/src/core/setupCode.js +331 -0
- package/src/core/shell.js +70 -7
- package/src/core/ssl-issuer.js +627 -0
- package/src/core/updater.js +295 -0
- package/src/core/validators.js +99 -0
- package/src/dashboard/controllers/authController.js +302 -15
- package/src/dashboard/controllers/deploymentsController.js +479 -0
- package/src/dashboard/controllers/domainsController.js +39 -52
- package/src/dashboard/controllers/hubController.js +135 -0
- package/src/dashboard/controllers/nginxController.js +21 -3
- package/src/dashboard/controllers/processesController.js +368 -0
- package/src/dashboard/controllers/settingsController.js +180 -12
- package/src/dashboard/controllers/sslController.js +171 -10
- package/src/dashboard/lib/daemonBridge.js +163 -0
- package/src/dashboard/lib/localRequest.js +235 -0
- package/src/dashboard/lib/loginRateLimit.js +119 -0
- package/src/dashboard/lib/requireAuth.js +80 -0
- package/src/dashboard/public/js/app.js +489 -19
- package/src/dashboard/routes/auth.js +10 -10
- package/src/dashboard/routes/deployments.js +46 -0
- package/src/dashboard/routes/domains.js +9 -0
- package/src/dashboard/routes/hub.js +22 -0
- package/src/dashboard/routes/nginx.js +9 -0
- package/src/dashboard/routes/processes.js +29 -0
- package/src/dashboard/routes/settings.js +9 -0
- package/src/dashboard/routes/ssl.js +9 -0
- package/src/dashboard/server.js +288 -21
- package/src/dashboard/socketManager.js +171 -207
- package/src/dashboard/views/index.ejs +1 -0
- package/src/dashboard/views/partials/login.ejs +68 -7
- package/src/dashboard/views/partials/processes-panel.ejs +261 -0
- package/src/dashboard/views/partials/settings-panel.ejs +287 -0
- package/src/dashboard/views/partials/sidebar.ejs +2 -0
- package/src/dashboard/lib/domains-db.js +0 -51
package/src/core/db.js
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
import { GoodDB, SQLiteDriver } from 'good.db';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
|
-
import os from 'os';
|
|
5
4
|
import { fileURLToPath } from 'url';
|
|
5
|
+
import { getDataDir, isDefaultDataDir } from './platform.js';
|
|
6
6
|
|
|
7
7
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
8
8
|
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
const DATA_DIR = process.platform === 'win32'
|
|
13
|
-
? path.join(process.env.APPDATA || os.homedir(), 'easy-devops')
|
|
14
|
-
: path.join(os.homedir(), '.config', 'easy-devops');
|
|
9
|
+
// Resolved once per process. The location lives in core/platform.js so the
|
|
10
|
+
// database, sessions and logs all agree on it — see getDataDir().
|
|
11
|
+
const DATA_DIR = getDataDir();
|
|
15
12
|
|
|
16
13
|
const DB_PATH = path.join(DATA_DIR, 'easy-devops.sqlite');
|
|
17
14
|
|
|
@@ -19,6 +16,19 @@ const DB_PATH = path.join(DATA_DIR, 'easy-devops.sqlite');
|
|
|
19
16
|
const OLD_DATA_DIR = path.join(__dirname, '..', '..', 'data');
|
|
20
17
|
const OLD_DB_PATH = path.join(OLD_DATA_DIR, 'easy-devops.sqlite');
|
|
21
18
|
function migrateIfNeeded() {
|
|
19
|
+
// Only ever migrate INTO the default data directory. The migration RENAMES
|
|
20
|
+
// the legacy database, so running against any other directory — `--dev`, a
|
|
21
|
+
// test's temp directory, or anything else pointed at by
|
|
22
|
+
// EASY_DEVOPS_DATA_DIR — would consume the real installation's data.
|
|
23
|
+
//
|
|
24
|
+
// This used to ask `isDevDataDir()`, which returned true for ANY redirected
|
|
25
|
+
// directory and so happened to express the same rule. It no longer does:
|
|
26
|
+
// dev mode is now about intent, and every installed service passes a data
|
|
27
|
+
// directory without being a dev run. `isDefaultDataDir()` states the actual
|
|
28
|
+
// requirement — "this is a real installation's own directory" — rather than
|
|
29
|
+
// relying on a second question that used to have the same answer.
|
|
30
|
+
if (!isDefaultDataDir(DATA_DIR)) return;
|
|
31
|
+
|
|
22
32
|
try {
|
|
23
33
|
if (fs.existsSync(OLD_DB_PATH) && !fs.existsSync(DB_PATH)) {
|
|
24
34
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
@@ -40,13 +50,32 @@ try {
|
|
|
40
50
|
|
|
41
51
|
let db;
|
|
42
52
|
|
|
53
|
+
/**
|
|
54
|
+
* The read cache is deliberately OFF.
|
|
55
|
+
*
|
|
56
|
+
* good.db's cache is a plain in-process LRU with no TTL and no invalidation
|
|
57
|
+
* across connections: the first `get` of a key stores the value, and every
|
|
58
|
+
* later `get` in that process returns it forever (the map holds 1024 entries
|
|
59
|
+
* and this app uses a handful of keys, so nothing is ever evicted).
|
|
60
|
+
*
|
|
61
|
+
* Easy DevOps runs as SEVERAL processes against ONE database file — the CLI,
|
|
62
|
+
* the dashboard (which hosts the hub agent) and any `ezz` invocation. With the
|
|
63
|
+
* cache on, a value written by the CLI was invisible to the running dashboard
|
|
64
|
+
* for the life of that process, so the agent's revision poll could never see a
|
|
65
|
+
* CLI-side change and those changes never reached the Hub.
|
|
66
|
+
*
|
|
67
|
+
* Measured cost of reading straight from SQLite: ~50us for a scalar key and
|
|
68
|
+
* ~150us for the whole domain list. The dashboard reads at a few hundred ops
|
|
69
|
+
* per minute, so this is invisible — and correctness here cannot be opted into
|
|
70
|
+
* per call site without every future caller having to remember.
|
|
71
|
+
*/
|
|
43
72
|
function createDbConnection() {
|
|
44
73
|
return new GoodDB(new SQLiteDriver({ path: DB_PATH }), {
|
|
45
74
|
nested: "..",
|
|
46
75
|
nestedIsEnabled: true,
|
|
47
76
|
cache: {
|
|
48
77
|
capacity: 1024,
|
|
49
|
-
isEnabled:
|
|
78
|
+
isEnabled: false,
|
|
50
79
|
}
|
|
51
80
|
});
|
|
52
81
|
}
|
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/deploy/apps.js
|
|
3
|
+
*
|
|
4
|
+
* The registry of deployed apps: what to fetch, how to authenticate, what to
|
|
5
|
+
* override, which environment to run with, and how a deployment may be
|
|
6
|
+
* triggered.
|
|
7
|
+
*
|
|
8
|
+
* Stored under the `deployApps` key in the database, like domains. It holds
|
|
9
|
+
* secrets — environment values, a GitHub token — because the server is the
|
|
10
|
+
* one place they have to exist. They never leave it in a Hub telemetry push
|
|
11
|
+
* (see publicApp()), and the deploy-hook token is not stored at all: only its
|
|
12
|
+
* SHA-256, since it is 256 bits of randomness and needs no slow hash.
|
|
13
|
+
*
|
|
14
|
+
* Everything that becomes part of a shell command or a path is validated HERE,
|
|
15
|
+
* once, on the way in: the id, the repository URL and the branch. The engine
|
|
16
|
+
* can then build commands from an app record without re-checking it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import crypto from 'crypto';
|
|
20
|
+
import fs from 'fs';
|
|
21
|
+
|
|
22
|
+
import { dbGet, dbSet } from '../db.js';
|
|
23
|
+
import { normalizeOverrides } from './ezfile.js';
|
|
24
|
+
import path from 'path';
|
|
25
|
+
import { appPaths, deployRoot, ensureAppDirs, removeAppFiles } from './store.js';
|
|
26
|
+
import { EZ_APP_NAMES } from '../runner.js';
|
|
27
|
+
|
|
28
|
+
const STORE_KEY = 'deployApps';
|
|
29
|
+
|
|
30
|
+
export const AUTH_TYPES = Object.freeze({ NONE: 'none', DEPLOY_KEY: 'deployKey', TOKEN: 'token' });
|
|
31
|
+
|
|
32
|
+
export const DEFAULT_KEEP_RELEASES = 5;
|
|
33
|
+
export const MIN_KEEP_RELEASES = 2;
|
|
34
|
+
export const MAX_KEEP_RELEASES = 20;
|
|
35
|
+
|
|
36
|
+
const MAX_ENV_VARS = 200;
|
|
37
|
+
const MAX_ENV_VALUE = 16 * 1024;
|
|
38
|
+
|
|
39
|
+
/** PM2 names every deployed app gets, so they are recognisable as ours. */
|
|
40
|
+
export const PM2_PREFIX = 'ez-';
|
|
41
|
+
|
|
42
|
+
/** @returns {string} The PM2 process name for an app id */
|
|
43
|
+
export function pm2Name(appId) {
|
|
44
|
+
return `${PM2_PREFIX}${appId}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ─── Validation ───────────────────────────────────────────────────────────────
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* An app id: lower-case letters, digits and dashes, 1–40 characters.
|
|
51
|
+
* It becomes a directory name, a PM2 name and a URL segment.
|
|
52
|
+
*
|
|
53
|
+
* @returns {string|null} An error message, or null when the id is acceptable
|
|
54
|
+
*/
|
|
55
|
+
export function validateAppId(id) {
|
|
56
|
+
if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,39}$/.test(id)) {
|
|
57
|
+
return 'The name must be 1–40 characters: lower-case letters, digits and dashes, starting with a letter or digit.';
|
|
58
|
+
}
|
|
59
|
+
if (id.endsWith('-')) return 'The name cannot end with a dash.';
|
|
60
|
+
// `ez-dashboard` is Easy DevOps' own PM2 app; an app called "dashboard"
|
|
61
|
+
// would take its name and be stopped by `ezz service` commands.
|
|
62
|
+
if (EZ_APP_NAMES.includes(pm2Name(id))) return `"${id}" is reserved.`;
|
|
63
|
+
if (id === 'hook') return '"hook" is reserved.';
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A repository URL git can fetch from: https, ssh://, or the scp-like
|
|
69
|
+
* `git@host:owner/repo.git`.
|
|
70
|
+
*
|
|
71
|
+
* The character set is deliberately narrow. This string is interpolated into
|
|
72
|
+
* a shell command, so quotes, spaces, `$`, backticks, `;`, `&`, `|` and the
|
|
73
|
+
* rest are refused outright rather than escaped — nothing a real repository
|
|
74
|
+
* URL needs is lost, and there is no quoting to get wrong per shell.
|
|
75
|
+
* Credentials embedded in the URL are refused too: they would be written to
|
|
76
|
+
* the deployment log.
|
|
77
|
+
*
|
|
78
|
+
* @returns {string|null} An error message, or null
|
|
79
|
+
*/
|
|
80
|
+
export function validateRepoUrl(url) {
|
|
81
|
+
if (typeof url !== 'string' || url.length === 0 || url.length > 500) return 'A repository URL is required.';
|
|
82
|
+
if (!/^[A-Za-z0-9@:/._~+-]+$/.test(url)) return 'The repository URL contains characters that are not allowed.';
|
|
83
|
+
if (url.startsWith('-')) return 'The repository URL is not valid.';
|
|
84
|
+
|
|
85
|
+
if (/^https:\/\//.test(url)) {
|
|
86
|
+
if (/^https:\/\/[^/]*@/.test(url)) return 'Do not put credentials in the URL — use a token or a deploy key instead.';
|
|
87
|
+
if (!/^https:\/\/[A-Za-z0-9.-]+(:[0-9]+)?\/[A-Za-z0-9._~+/-]+$/.test(url)) return 'The repository URL is not valid.';
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (/^ssh:\/\//.test(url)) {
|
|
91
|
+
if (!/^ssh:\/\/[A-Za-z0-9._-]+@[A-Za-z0-9.-]+(:[0-9]+)?\/[A-Za-z0-9._~+/-]+$/.test(url)) return 'The repository URL is not valid.';
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
if (/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[A-Za-z0-9._~+/-]+$/.test(url)) return null;
|
|
95
|
+
|
|
96
|
+
return 'Use an https:// URL, an ssh:// URL, or the git@host:owner/repo.git form.';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** True for a URL git reaches over SSH. */
|
|
100
|
+
export function isSshUrl(url) {
|
|
101
|
+
return /^ssh:\/\//.test(String(url)) || /^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:/.test(String(url));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A branch name, tag or commit SHA.
|
|
106
|
+
* @returns {string|null} An error message, or null
|
|
107
|
+
*/
|
|
108
|
+
export function validateRef(ref) {
|
|
109
|
+
if (typeof ref !== 'string' || ref.length === 0 || ref.length > 200) return 'A branch is required.';
|
|
110
|
+
if (!/^[A-Za-z0-9._/-]+$/.test(ref) || ref.startsWith('-') || ref.includes('..')) {
|
|
111
|
+
return 'The branch name contains characters that are not allowed.';
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Environment variables: `{ NAME: "value" }`.
|
|
118
|
+
* @returns {{ ok: boolean, value: Object<string,string>, error: string|null }}
|
|
119
|
+
*/
|
|
120
|
+
export function normalizeEnv(input) {
|
|
121
|
+
if (input === undefined || input === null) return { ok: true, value: {}, error: null };
|
|
122
|
+
if (typeof input !== 'object' || Array.isArray(input)) return { ok: false, value: {}, error: 'env must be an object of NAME: value pairs' };
|
|
123
|
+
|
|
124
|
+
const entries = Object.entries(input);
|
|
125
|
+
if (entries.length > MAX_ENV_VARS) return { ok: false, value: {}, error: `At most ${MAX_ENV_VARS} environment variables are allowed.` };
|
|
126
|
+
|
|
127
|
+
const value = {};
|
|
128
|
+
for (const [name, raw] of entries) {
|
|
129
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
130
|
+
return { ok: false, value: {}, error: `"${name}" is not a valid variable name (letters, digits and underscores, not starting with a digit).` };
|
|
131
|
+
}
|
|
132
|
+
if (raw === null || raw === undefined) continue;
|
|
133
|
+
if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean') {
|
|
134
|
+
return { ok: false, value: {}, error: `The value of ${name} must be text.` };
|
|
135
|
+
}
|
|
136
|
+
const text = String(raw);
|
|
137
|
+
if (text.length > MAX_ENV_VALUE) return { ok: false, value: {}, error: `The value of ${name} is too long.` };
|
|
138
|
+
if (text.includes('\0')) return { ok: false, value: {}, error: `The value of ${name} contains a NUL character.` };
|
|
139
|
+
value[name] = text;
|
|
140
|
+
}
|
|
141
|
+
return { ok: true, value, error: null };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function normalizeKeep(value) {
|
|
145
|
+
if (value === undefined || value === null || value === '') return DEFAULT_KEEP_RELEASES;
|
|
146
|
+
const n = Number(value);
|
|
147
|
+
if (!Number.isInteger(n) || n < MIN_KEEP_RELEASES || n > MAX_KEEP_RELEASES) return null;
|
|
148
|
+
return n;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ─── Storage ──────────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
/** @returns {Array<Object>} */
|
|
154
|
+
export function listApps() {
|
|
155
|
+
const raw = dbGet(STORE_KEY);
|
|
156
|
+
return Array.isArray(raw) ? raw : [];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function saveApps(apps) {
|
|
160
|
+
dbSet(STORE_KEY, apps);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** @returns {Object|null} */
|
|
164
|
+
export function getApp(id) {
|
|
165
|
+
return listApps().find((a) => a.id === id) ?? null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Validates the editable fields of an app.
|
|
170
|
+
*
|
|
171
|
+
* `existing` makes it an update: fields that are absent keep their current
|
|
172
|
+
* value, and the token is kept unless a new one is supplied — so the UI never
|
|
173
|
+
* has to round-trip a secret just to change the branch.
|
|
174
|
+
*
|
|
175
|
+
* @returns {{ ok: boolean, value: Object|null, errors: string[] }}
|
|
176
|
+
*/
|
|
177
|
+
export function normalizeAppInput(input, existing = null) {
|
|
178
|
+
const errors = [];
|
|
179
|
+
const src = input && typeof input === 'object' ? input : {};
|
|
180
|
+
const has = (k) => src[k] !== undefined;
|
|
181
|
+
|
|
182
|
+
const repoUrl = has('repoUrl') ? String(src.repoUrl ?? '').trim() : existing?.repoUrl;
|
|
183
|
+
const repoError = validateRepoUrl(repoUrl);
|
|
184
|
+
if (repoError) errors.push(repoError);
|
|
185
|
+
|
|
186
|
+
const branch = has('branch') ? String(src.branch ?? '').trim() || 'main' : (existing?.branch ?? 'main');
|
|
187
|
+
const refError = validateRef(branch);
|
|
188
|
+
if (refError) errors.push(refError);
|
|
189
|
+
|
|
190
|
+
// ── how the server authenticates to the repository
|
|
191
|
+
const authType = has('authType') ? src.authType : (existing?.auth?.type ?? AUTH_TYPES.NONE);
|
|
192
|
+
if (!Object.values(AUTH_TYPES).includes(authType)) errors.push('authType must be none, deployKey or token.');
|
|
193
|
+
|
|
194
|
+
let token = existing?.auth?.token ?? null;
|
|
195
|
+
if (has('token') && src.token !== null && src.token !== '') {
|
|
196
|
+
const t = String(src.token).trim();
|
|
197
|
+
// The token goes into an HTTP header on the git command line.
|
|
198
|
+
if (!/^[A-Za-z0-9_.-]{10,255}$/.test(t)) errors.push('The token contains characters that are not allowed.');
|
|
199
|
+
else token = t;
|
|
200
|
+
}
|
|
201
|
+
if (authType === AUTH_TYPES.TOKEN) {
|
|
202
|
+
if (!token) errors.push('A token is required for token authentication.');
|
|
203
|
+
if (repoUrl && isSshUrl(repoUrl)) errors.push('Token authentication needs an https:// repository URL.');
|
|
204
|
+
}
|
|
205
|
+
if (authType === AUTH_TYPES.DEPLOY_KEY && repoUrl && !isSshUrl(repoUrl)) {
|
|
206
|
+
errors.push('A deploy key needs an SSH repository URL (git@github.com:owner/repo.git).');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const overrides = has('settings') ? normalizeOverrides(src.settings) : { ok: true, value: existing?.settings ?? {}, errors: [] };
|
|
210
|
+
for (const e of overrides.errors) errors.push(e);
|
|
211
|
+
|
|
212
|
+
const env = has('env') ? normalizeEnv(src.env) : { ok: true, value: existing?.env ?? {}, error: null };
|
|
213
|
+
if (env.error) errors.push(env.error);
|
|
214
|
+
|
|
215
|
+
const keepReleases = has('keepReleases') ? normalizeKeep(src.keepReleases) : (existing?.keepReleases ?? DEFAULT_KEEP_RELEASES);
|
|
216
|
+
if (keepReleases === null) errors.push(`keepReleases must be a whole number from ${MIN_KEEP_RELEASES} to ${MAX_KEEP_RELEASES}.`);
|
|
217
|
+
|
|
218
|
+
const autoRollback = has('autoRollback') ? src.autoRollback : (existing?.autoRollback ?? true);
|
|
219
|
+
if (typeof autoRollback !== 'boolean') errors.push('autoRollback must be true or false.');
|
|
220
|
+
|
|
221
|
+
let notifyChannelIds = existing?.notifyChannelIds ?? [];
|
|
222
|
+
if (has('notifyChannelIds')) {
|
|
223
|
+
if (!Array.isArray(src.notifyChannelIds) || src.notifyChannelIds.some((c) => typeof c !== 'string')) {
|
|
224
|
+
errors.push('notifyChannelIds must be a list of channel ids.');
|
|
225
|
+
} else {
|
|
226
|
+
notifyChannelIds = [...new Set(src.notifyChannelIds)];
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (errors.length > 0) return { ok: false, value: null, errors };
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
ok: true,
|
|
234
|
+
errors,
|
|
235
|
+
value: {
|
|
236
|
+
repoUrl,
|
|
237
|
+
branch,
|
|
238
|
+
auth: {
|
|
239
|
+
type: authType,
|
|
240
|
+
// Kept even when another type is selected, so switching back does not
|
|
241
|
+
// need the secret entered again. Only used when the type says so.
|
|
242
|
+
token,
|
|
243
|
+
publicKey: existing?.auth?.publicKey ?? null,
|
|
244
|
+
},
|
|
245
|
+
settings: overrides.value,
|
|
246
|
+
env: env.value,
|
|
247
|
+
keepReleases,
|
|
248
|
+
autoRollback,
|
|
249
|
+
notifyChannelIds,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Creates an app.
|
|
256
|
+
* @returns {{ ok: true, app: Object } | { ok: false, errors: string[], status: number }}
|
|
257
|
+
*/
|
|
258
|
+
export function createApp(input) {
|
|
259
|
+
const id = String(input?.id ?? '').trim();
|
|
260
|
+
const idError = validateAppId(id);
|
|
261
|
+
if (idError) return { ok: false, errors: [idError], status: 400 };
|
|
262
|
+
|
|
263
|
+
const apps = listApps();
|
|
264
|
+
if (apps.some((a) => a.id === id)) return { ok: false, errors: [`An app named "${id}" already exists.`], status: 409 };
|
|
265
|
+
|
|
266
|
+
const normalized = normalizeAppInput(input);
|
|
267
|
+
if (!normalized.ok) return { ok: false, errors: normalized.errors, status: 400 };
|
|
268
|
+
|
|
269
|
+
const now = new Date().toISOString();
|
|
270
|
+
const app = {
|
|
271
|
+
id,
|
|
272
|
+
...normalized.value,
|
|
273
|
+
// Recorded once, here: the app keeps living in this folder even if the
|
|
274
|
+
// deployments-folder setting changes later. Only a move changes it.
|
|
275
|
+
dir: path.join(deployRoot(), id),
|
|
276
|
+
// The domain that proxies to this app, when one is linked (domainLink.js).
|
|
277
|
+
domain: null,
|
|
278
|
+
hook: { tokenHash: null, tokenHint: null, createdAt: null },
|
|
279
|
+
createdAt: now,
|
|
280
|
+
updatedAt: now,
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// Saved first: store.js resolves an app's folder from its record.
|
|
284
|
+
saveApps([...apps, app]);
|
|
285
|
+
try {
|
|
286
|
+
ensureAppDirs(id);
|
|
287
|
+
} catch (err) {
|
|
288
|
+
saveApps(apps);
|
|
289
|
+
return { ok: false, errors: [`Could not create ${app.dir}: ${err.message}`], status: 500 };
|
|
290
|
+
}
|
|
291
|
+
return { ok: true, app };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Updates an app's editable fields.
|
|
296
|
+
* @returns {{ ok: true, app: Object } | { ok: false, errors: string[], status: number }}
|
|
297
|
+
*/
|
|
298
|
+
export function updateApp(id, input) {
|
|
299
|
+
const apps = listApps();
|
|
300
|
+
const index = apps.findIndex((a) => a.id === id);
|
|
301
|
+
if (index === -1) return { ok: false, errors: [`No app named "${id}".`], status: 404 };
|
|
302
|
+
|
|
303
|
+
const normalized = normalizeAppInput(input, apps[index]);
|
|
304
|
+
if (!normalized.ok) return { ok: false, errors: normalized.errors, status: 400 };
|
|
305
|
+
|
|
306
|
+
const app = { ...apps[index], ...normalized.value, updatedAt: new Date().toISOString() };
|
|
307
|
+
apps[index] = app;
|
|
308
|
+
saveApps(apps);
|
|
309
|
+
return { ok: true, app };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Records a new folder for an app after it has been moved. */
|
|
313
|
+
export function setAppDir(id, dir) {
|
|
314
|
+
return patchApp(id, { dir });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Records (or clears) the domain linked to an app. */
|
|
318
|
+
export function setAppDomain(id, domain) {
|
|
319
|
+
return patchApp(id, { domain: domain ?? null });
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Low-level patch for fields this module owns (hook token, deploy key, folder, domain). */
|
|
323
|
+
function patchApp(id, patch) {
|
|
324
|
+
const apps = listApps();
|
|
325
|
+
const index = apps.findIndex((a) => a.id === id);
|
|
326
|
+
if (index === -1) return null;
|
|
327
|
+
apps[index] = { ...apps[index], ...patch, updatedAt: new Date().toISOString() };
|
|
328
|
+
saveApps(apps);
|
|
329
|
+
return apps[index];
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Removes an app from the registry and deletes its files.
|
|
334
|
+
* Stopping its PM2 process is the caller's job (core/deploy/engine.js).
|
|
335
|
+
* @returns {boolean} Whether an app was removed
|
|
336
|
+
*/
|
|
337
|
+
export function deleteApp(id) {
|
|
338
|
+
const apps = listApps();
|
|
339
|
+
if (!apps.some((a) => a.id === id)) return false;
|
|
340
|
+
// Files first: once the record is gone, nothing remembers which folder was its.
|
|
341
|
+
try { removeAppFiles(id); } catch { /* files in use: the registry entry is removed regardless */ }
|
|
342
|
+
saveApps(apps.filter((a) => a.id !== id));
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ─── The deploy-hook token ────────────────────────────────────────────────────
|
|
347
|
+
|
|
348
|
+
function sha256(text) {
|
|
349
|
+
return crypto.createHash('sha256').update(String(text)).digest('hex');
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Issues a new deploy-hook token for an app, replacing any earlier one.
|
|
354
|
+
*
|
|
355
|
+
* The cleartext is returned ONCE, to be shown to the user and pasted into the
|
|
356
|
+
* repository's secrets. Only its hash is stored, so a copy of the database is
|
|
357
|
+
* not a set of working deploy credentials.
|
|
358
|
+
*
|
|
359
|
+
* @returns {{ token: string, hint: string } | null} null when the app does not exist
|
|
360
|
+
*/
|
|
361
|
+
export function rotateHookToken(id) {
|
|
362
|
+
const token = `ezd_${crypto.randomBytes(32).toString('base64url')}`;
|
|
363
|
+
const hint = token.slice(-4);
|
|
364
|
+
const app = patchApp(id, {
|
|
365
|
+
hook: { tokenHash: sha256(token), tokenHint: hint, createdAt: new Date().toISOString() },
|
|
366
|
+
});
|
|
367
|
+
return app ? { token, hint } : null;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Removes the token, which disables the hook for this app. */
|
|
371
|
+
export function revokeHookToken(id) {
|
|
372
|
+
return Boolean(patchApp(id, { hook: { tokenHash: null, tokenHint: null, createdAt: null } }));
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Constant-time check of a presented token against an app's stored hash.
|
|
377
|
+
* @returns {boolean}
|
|
378
|
+
*/
|
|
379
|
+
export function verifyHookToken(app, presented) {
|
|
380
|
+
const stored = app?.hook?.tokenHash;
|
|
381
|
+
if (!stored || typeof presented !== 'string' || presented.length === 0 || presented.length > 512) return false;
|
|
382
|
+
const a = Buffer.from(sha256(presented), 'hex');
|
|
383
|
+
const b = Buffer.from(stored, 'hex');
|
|
384
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ─── The deploy key ───────────────────────────────────────────────────────────
|
|
388
|
+
|
|
389
|
+
/** SSH wire encoding of a length-prefixed byte string. */
|
|
390
|
+
function sshString(buf) {
|
|
391
|
+
const len = Buffer.alloc(4);
|
|
392
|
+
len.writeUInt32BE(buf.length);
|
|
393
|
+
return Buffer.concat([len, buf]);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** SSH wire encoding of a positive big integer (a leading zero if the top bit is set). */
|
|
397
|
+
function sshMpint(buf) {
|
|
398
|
+
let b = buf;
|
|
399
|
+
while (b.length > 1 && b[0] === 0) b = b.subarray(1);
|
|
400
|
+
if (b[0] & 0x80) b = Buffer.concat([Buffer.from([0]), b]);
|
|
401
|
+
return sshString(b);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Generates an RSA key pair for an app and stores the private half on disk.
|
|
406
|
+
*
|
|
407
|
+
* Generated in-process rather than with `ssh-keygen`, so it does not depend on
|
|
408
|
+
* which OpenSSH tools a machine has. RSA-4096 with a PKCS#1 PEM private key is
|
|
409
|
+
* the one format every OpenSSH client reads, on both platforms.
|
|
410
|
+
*
|
|
411
|
+
* The public key is returned and stored; the private key is written with
|
|
412
|
+
* owner-only permissions and never returned by any API.
|
|
413
|
+
*
|
|
414
|
+
* @returns {{ publicKey: string } | null} null when the app does not exist
|
|
415
|
+
*/
|
|
416
|
+
export function generateDeployKey(id) {
|
|
417
|
+
if (!getApp(id)) return null;
|
|
418
|
+
|
|
419
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
|
|
420
|
+
modulusLength: 4096,
|
|
421
|
+
publicKeyEncoding: { type: 'spki', format: 'pem' },
|
|
422
|
+
privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
const jwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
|
|
426
|
+
const blob = Buffer.concat([
|
|
427
|
+
sshString(Buffer.from('ssh-rsa')),
|
|
428
|
+
sshMpint(Buffer.from(jwk.e, 'base64url')),
|
|
429
|
+
sshMpint(Buffer.from(jwk.n, 'base64url')),
|
|
430
|
+
]);
|
|
431
|
+
const sshPublic = `ssh-rsa ${blob.toString('base64')} easy-devops-deploy-${id}`;
|
|
432
|
+
|
|
433
|
+
const p = ensureAppDirs(id);
|
|
434
|
+
fs.writeFileSync(p.deployKey, privateKey, { mode: 0o600 });
|
|
435
|
+
try { fs.chmodSync(p.deployKey, 0o600); } catch { /* not meaningful on Windows */ }
|
|
436
|
+
|
|
437
|
+
const app = getApp(id);
|
|
438
|
+
patchApp(id, { auth: { ...(app.auth ?? {}), publicKey: sshPublic } });
|
|
439
|
+
return { publicKey: sshPublic };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Path of an app's private deploy key, or null when it has none on disk. */
|
|
443
|
+
export function deployKeyPath(id) {
|
|
444
|
+
const file = appPaths(id).deployKey;
|
|
445
|
+
return fs.existsSync(file) ? file : null;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ─── What may be shown ────────────────────────────────────────────────────────
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* The app as the local dashboard may see it: everything except the secrets
|
|
452
|
+
* that have no reason to be read back. Environment values ARE included — the
|
|
453
|
+
* dashboard is where they are edited, behind its own login.
|
|
454
|
+
*/
|
|
455
|
+
export function dashboardApp(app) {
|
|
456
|
+
if (!app) return null;
|
|
457
|
+
return {
|
|
458
|
+
id: app.id,
|
|
459
|
+
pm2Name: pm2Name(app.id),
|
|
460
|
+
repoUrl: app.repoUrl,
|
|
461
|
+
branch: app.branch,
|
|
462
|
+
authType: app.auth?.type ?? AUTH_TYPES.NONE,
|
|
463
|
+
hasToken: Boolean(app.auth?.token),
|
|
464
|
+
deployKey: app.auth?.publicKey ?? null,
|
|
465
|
+
settings: app.settings ?? {},
|
|
466
|
+
env: app.env ?? {},
|
|
467
|
+
keepReleases: app.keepReleases ?? DEFAULT_KEEP_RELEASES,
|
|
468
|
+
autoRollback: app.autoRollback !== false,
|
|
469
|
+
notifyChannelIds: app.notifyChannelIds ?? [],
|
|
470
|
+
dir: appPaths(app.id).root,
|
|
471
|
+
domain: app.domain ?? null,
|
|
472
|
+
hook: {
|
|
473
|
+
hasToken: Boolean(app.hook?.tokenHash),
|
|
474
|
+
tokenHint: app.hook?.tokenHint ?? null,
|
|
475
|
+
createdAt: app.hook?.createdAt ?? null,
|
|
476
|
+
},
|
|
477
|
+
createdAt: app.createdAt ?? null,
|
|
478
|
+
updatedAt: app.updatedAt ?? null,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* The app as it may leave the server (Hub telemetry): no environment VALUES,
|
|
484
|
+
* only their names, and no credentials of any kind.
|
|
485
|
+
*/
|
|
486
|
+
export function publicApp(app) {
|
|
487
|
+
const d = dashboardApp(app);
|
|
488
|
+
if (!d) return null;
|
|
489
|
+
const { env, ...rest } = d;
|
|
490
|
+
return { ...rest, envKeys: Object.keys(env).sort() };
|
|
491
|
+
}
|