@geekmidas/cli 10.0.0-alpha.111 → 10.0.0-alpha.113

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 (37) hide show
  1. package/dist/{cli-Br5ApIgR.mjs → cli-DDY3jfTt.mjs} +3 -3
  2. package/dist/{cli-Br5ApIgR.mjs.map → cli-DDY3jfTt.mjs.map} +1 -1
  3. package/dist/{eas-BkLA60P2.cjs → eas-Cne743nQ.cjs} +21 -3
  4. package/dist/eas-Cne743nQ.cjs.map +1 -0
  5. package/dist/{eas-6ezdJtry.mjs → eas-DEpwISrQ.mjs} +25 -7
  6. package/dist/eas-DEpwISrQ.mjs.map +1 -0
  7. package/dist/{github-D2eABlxM.mjs → github-BMakI-k3.mjs} +5 -4
  8. package/dist/github-BMakI-k3.mjs.map +1 -0
  9. package/dist/{github-DDOHjdS9.cjs → github-C3gblUvr.cjs} +5 -3
  10. package/dist/github-C3gblUvr.cjs.map +1 -0
  11. package/dist/{googlePlay-DNgybe5t.cjs → googlePlay-B6uiHi65.cjs} +2 -2
  12. package/dist/{googlePlay-DNgybe5t.cjs.map → googlePlay-B6uiHi65.cjs.map} +1 -1
  13. package/dist/{googlePlay-DY9vZQ1p.mjs → googlePlay-BYZ-J5sC.mjs} +4 -4
  14. package/dist/{googlePlay-DY9vZQ1p.mjs.map → googlePlay-BYZ-J5sC.mjs.map} +1 -1
  15. package/dist/index.cjs +167 -74
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.mjs +176 -85
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{migrate-B9GswIAr.mjs → migrate-xHYaeBkd.mjs} +2 -2
  20. package/dist/{migrate-B9GswIAr.mjs.map → migrate-xHYaeBkd.mjs.map} +1 -1
  21. package/dist/{publish-B-EIjfQ0.mjs → publish-CSctCNf4.mjs} +2 -2
  22. package/dist/{publish-B-EIjfQ0.mjs.map → publish-CSctCNf4.mjs.map} +1 -1
  23. package/dist/{publish-CPgSbtcs.cjs → publish-SDG1WfYn.cjs} +2 -2
  24. package/dist/{publish-CPgSbtcs.cjs.map → publish-SDG1WfYn.cjs.map} +1 -1
  25. package/dist/serverSetup--O61SRvg.mjs +558 -0
  26. package/dist/serverSetup--O61SRvg.mjs.map +1 -0
  27. package/dist/serverSetup-BCbD8ksJ.cjs +558 -0
  28. package/dist/serverSetup-BCbD8ksJ.cjs.map +1 -0
  29. package/dist/{stage-DjxR_7C0.mjs → stage-ClKTHQoM.mjs} +2 -2
  30. package/dist/{stage-DjxR_7C0.mjs.map → stage-ClKTHQoM.mjs.map} +1 -1
  31. package/dist/{terminal-mXM-Lqc6.mjs → terminal-CybB-cjk.mjs} +2 -2
  32. package/dist/{terminal-mXM-Lqc6.mjs.map → terminal-CybB-cjk.mjs.map} +1 -1
  33. package/package.json +15 -15
  34. package/dist/eas-6ezdJtry.mjs.map +0 -1
  35. package/dist/eas-BkLA60P2.cjs.map +0 -1
  36. package/dist/github-D2eABlxM.mjs.map +0 -1
  37. package/dist/github-DDOHjdS9.cjs.map +0 -1
@@ -0,0 +1,558 @@
1
+ import { t as GkmError } from "./errors-D8Gwp5kU.mjs";
2
+ import { y as composeServer } from "./compose-CDC2bCme.mjs";
3
+ import { N as assertDeployedStage } from "./workspace-D1QbNd55.mjs";
4
+ import { It as secretsStoreFor } from "./seeds-CIk0l4SC.mjs";
5
+ import { loadWorkspaceConfig } from "./config.mjs";
6
+ import { u as prompt } from "./index.mjs";
7
+ import { ghCli } from "./github-BMakI-k3.mjs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { existsSync } from "node:fs";
10
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
11
+ import { homedir } from "node:os";
12
+ import { spawn } from "node:child_process";
13
+ //#region src/compose/serverScript.ts
14
+ /**
15
+ * What `gkm compose:server` runs on the server, as root (through the admin
16
+ * user's sudo). Plain bash, so `--dry-run` can print exactly what will run,
17
+ * and safe to run again: every step changes only what is missing or wrong.
18
+ *
19
+ * Arguments, in order: the admin user (the one running sudo), the deploy
20
+ * user, the SSH port, the deploy key's public line, and its comment.
21
+ *
22
+ * The last line it prints is `HOSTKEY=<fingerprint>` — the server's own
23
+ * ed25519 host key, which the command checks the network's against before
24
+ * pinning it for CI.
25
+ */
26
+ const SERVER_SCRIPT = String.raw`set -euo pipefail
27
+ export DEBIAN_FRONTEND=noninteractive
28
+ ADMIN="$1"; DEPLOY="$2"; SSH_PORT="$3"; PUB="$4"; COMMENT="$5"
29
+ say() { echo " $*"; }
30
+ fail() { echo " ✗ $*" >&2; exit 1; }
31
+
32
+ . /etc/os-release
33
+ case "$ID" in
34
+ ubuntu | debian) ;;
35
+ *) fail "gkm sets up Ubuntu and Debian servers; this one is $ID." ;;
36
+ esac
37
+
38
+ # ── SSH: keys only, no root ────────────────────────────────────────────────
39
+ # Before password logins are turned off, the admin must have a key to come
40
+ # back with — otherwise this would lock them out.
41
+ ADMIN_HOME="$(getent passwd "$ADMIN" | cut -d: -f6)"
42
+ [ -s "$ADMIN_HOME/.ssh/authorized_keys" ] ||
43
+ fail "$ADMIN has no key in $ADMIN_HOME/.ssh/authorized_keys; turning off password logins would lock them out."
44
+ # First match wins in sshd_config, and 00- sorts before what a provider ships
45
+ # (cloud-init's 50-cloud-init.conf turns password logins back on).
46
+ cat > /etc/ssh/sshd_config.d/00-gkm-hardening.conf <<'EOF'
47
+ # Written by gkm compose:server.
48
+ PermitRootLogin no
49
+ PasswordAuthentication no
50
+ KbdInteractiveAuthentication no
51
+ EOF
52
+ # The deploy migrates through an SSH tunnel to the server's loopback.
53
+ cat > /etc/ssh/sshd_config.d/60-gkm-deploy.conf <<EOF
54
+ # Written by gkm compose:server.
55
+ Match User $DEPLOY
56
+ AllowTcpForwarding local
57
+ EOF
58
+ sshd -t
59
+ systemctl reload ssh 2>/dev/null || systemctl reload sshd
60
+ # What sshd actually does now, whatever else is in its config.
61
+ EFFECTIVE="$(sshd -T)"
62
+ for setting in 'permitrootlogin no' 'passwordauthentication no' 'kbdinteractiveauthentication no'; do
63
+ grep -qx "$setting" <<<"$EFFECTIVE" || fail "sshd still does not say '$setting'; another file in /etc/ssh overrides it."
64
+ done
65
+ FORWARD="$(sshd -T -C "user=$DEPLOY,host=localhost,addr=127.0.0.1" | sed -n 's/^allowtcpforwarding //p')"
66
+ case "$FORWARD" in
67
+ yes | all | local) ;;
68
+ *) fail "sshd does not let $DEPLOY forward ports (allowtcpforwarding $FORWARD)." ;;
69
+ esac
70
+ say "sshd: keys only, no root login; $DEPLOY may open local tunnels"
71
+
72
+ # ── Firewall: SSH, HTTP, HTTPS ─────────────────────────────────────────────
73
+ command -v ufw >/dev/null || { apt-get update -qq && apt-get install -y -qq ufw >/dev/null; }
74
+ ufw default deny incoming >/dev/null
75
+ ufw default allow outgoing >/dev/null
76
+ ufw allow "$SSH_PORT/tcp" >/dev/null
77
+ ufw allow 80/tcp >/dev/null
78
+ ufw allow 443/tcp >/dev/null
79
+ ufw --force enable >/dev/null
80
+ say "firewall: $SSH_PORT, 80, 443 in; everything out"
81
+ EXTRA="$(ufw status | awk 'NR > 4 && $1 != "" { print $1 }' | grep -vxE "(($SSH_PORT|80|443)(/tcp)?|OpenSSH)" | sort -u || true)"
82
+ if [ -n "$EXTRA" ]; then
83
+ say "⚠ also open: $(echo $EXTRA). gkm uses none of them; close each with: sudo ufw delete allow <port>"
84
+ fi
85
+
86
+ # ── Updates and bans ───────────────────────────────────────────────────────
87
+ apt-get update -qq
88
+ apt-get install -y -qq unattended-upgrades fail2ban >/dev/null
89
+ cat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'
90
+ APT::Periodic::Update-Package-Lists "1";
91
+ APT::Periodic::Unattended-Upgrade "1";
92
+ EOF
93
+ cat > /etc/fail2ban/jail.d/gkm.local <<EOF
94
+ # Written by gkm compose:server.
95
+ [sshd]
96
+ enabled = true
97
+ port = $SSH_PORT
98
+ EOF
99
+ systemctl enable --now unattended-upgrades fail2ban >/dev/null 2>&1
100
+ systemctl restart fail2ban
101
+ say "security updates install daily; fail2ban watches sshd"
102
+
103
+ # ── Docker, from Docker's own repository ───────────────────────────────────
104
+ if ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then
105
+ say "installing Docker…"
106
+ apt-get install -y -qq ca-certificates curl >/dev/null
107
+ install -m 0755 -d /etc/apt/keyrings
108
+ curl -fsSL "https://download.docker.com/linux/$ID/gpg" -o /etc/apt/keyrings/docker.asc
109
+ chmod a+r /etc/apt/keyrings/docker.asc
110
+ echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable" \
111
+ > /etc/apt/sources.list.d/docker.list
112
+ apt-get update -qq
113
+ apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null
114
+ fi
115
+ systemctl enable --now docker >/dev/null 2>&1
116
+ say "docker $(docker version --format '{{.Server.Version}}')"
117
+
118
+ # ── The deploy user: no password, no sudo, in the docker group ─────────────
119
+ id "$DEPLOY" >/dev/null 2>&1 || adduser --disabled-password --gecos "" "$DEPLOY" >/dev/null
120
+ usermod -aG docker "$DEPLOY"
121
+ DEPLOY_HOME="$(getent passwd "$DEPLOY" | cut -d: -f6)"
122
+ install -d -m 700 -o "$DEPLOY" -g "$DEPLOY" "$DEPLOY_HOME/.ssh"
123
+ AUTH="$DEPLOY_HOME/.ssh/authorized_keys"
124
+ touch "$AUTH"
125
+ # One managed line: this key (or an earlier one by the same name) replaced,
126
+ # with nothing allowed but the commands and the tunnel the deploy uses.
127
+ KEYBODY="$(awk '{ print $2 }' <<<"$PUB")"
128
+ grep -v -F -e "$KEYBODY" -e " $COMMENT" "$AUTH" > "$AUTH.new" || true
129
+ echo "restrict,port-forwarding $PUB" >> "$AUTH.new"
130
+ mv "$AUTH.new" "$AUTH"
131
+ chown "$DEPLOY:$DEPLOY" "$AUTH"
132
+ chmod 600 "$AUTH"
133
+ say "user $DEPLOY (docker group), deploy key authorized with restrict,port-forwarding"
134
+ OTHERS="$(grep -v -F -e "$KEYBODY" "$AUTH" | grep -c . || true)"
135
+ if [ "$OTHERS" -gt 0 ]; then
136
+ say "⚠ $AUTH holds $OTHERS other key(s). Review: sudo cat $AUTH"
137
+ fi
138
+
139
+ echo "HOSTKEY=$(ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | awk '{ print $2 }')"
140
+ `;
141
+ /**
142
+ * What runs as root to give a fresh server its admin — the guide's first
143
+ * step, for a server only root can log in to yet: a sudo user, with root's
144
+ * keys so the same key logs in. `adduser` asks for its password, which sudo
145
+ * will ask for.
146
+ */
147
+ const ADMIN_SCRIPT = `set -euo pipefail
148
+ ADMIN="$1"
149
+ if ! id "$ADMIN" >/dev/null 2>&1; then
150
+ echo " creating $ADMIN — choose the password sudo will ask for:"
151
+ adduser --gecos "" "$ADMIN"
152
+ fi
153
+ usermod -aG sudo "$ADMIN"
154
+ HOME_DIR="$(getent passwd "$ADMIN" | cut -d: -f6)"
155
+ install -d -m 700 -o "$ADMIN" -g "$ADMIN" "$HOME_DIR/.ssh"
156
+ AUTH="$HOME_DIR/.ssh/authorized_keys"
157
+ touch "$AUTH"
158
+ # The keys alone: a provider's options on root's lines (a command="…" that
159
+ # says "log in as ubuntu") would stop the admin's login too.
160
+ { grep -oE '(ssh|ecdsa|sk)-[^ ]+ [A-Za-z0-9+/=]+( .*)?$' /root/.ssh/authorized_keys || true; } |
161
+ while IFS= read -r key; do
162
+ grep -qxF "$key" "$AUTH" || echo "$key" >> "$AUTH"
163
+ done
164
+ chown "$ADMIN:$ADMIN" "$AUTH"
165
+ chmod 600 "$AUTH"
166
+ echo " $ADMIN is a sudo user, with root's SSH keys"
167
+ `;
168
+ //#endregion
169
+ //#region src/compose/serverSetup.ts
170
+ /**
171
+ * `gkm compose:server` — make a VPS ready for a stage's compose deploys, from
172
+ * this machine, in one go.
173
+ *
174
+ * It logs in as the server's admin — a sudo user, never root — and, through
175
+ * sudo, sets the server up the way a production VPS should be: SSH by key
176
+ * only with root's login off, a firewall open on SSH, 80 and 443 alone,
177
+ * security updates installed daily, fail2ban on sshd, and Docker from
178
+ * Docker's own repository. It then creates the stage's deploy user (in the
179
+ * docker group, no sudo, no password) and authorizes a deploy key on it that
180
+ * may run commands and open the tunnel migrations use, nothing more.
181
+ *
182
+ * Off the server: it makes the deploy key pair here, pins the server's host
183
+ * key — checked against the fingerprint the server reports of itself — and
184
+ * gives both to the stage's GitHub environment as `DEPLOY_SSH_KEY` and
185
+ * `DEPLOY_KNOWN_HOSTS`, which the generated deploy workflow reads. Last, it
186
+ * logs in exactly as CI will, and checks Docker and the tunnel answer.
187
+ *
188
+ * A fresh server only root can log in to gets its admin first: with root's
189
+ * key it creates the user, or with the admin's password it copies a key in.
190
+ * Safe to run again: each step changes only what is missing or wrong.
191
+ */
192
+ /** The admin named is root, whose login this command turns off. */
193
+ var ComposeServerAdminIsRoot = class extends GkmError {
194
+ constructor() {
195
+ super("The admin can't be root: setting up the server turns root's SSH login off. Name the sudo user you log in as (--admin <user>). A fresh server with only root gets one: run this again with the name it should have, and gkm offers to create it with root's key.");
196
+ this.name = "ComposeServerAdminIsRoot";
197
+ }
198
+ };
199
+ /** The admin named is the deploy user, which has no sudo. */
200
+ var ComposeServerAdminIsDeployUser = class extends GkmError {
201
+ user;
202
+ constructor(user) {
203
+ super(`'${user}' is the stage's deploy user (deploy.compose.server), which gkm creates without sudo. Name the sudo user you log in as with --admin.`);
204
+ this.user = user;
205
+ this.name = "ComposeServerAdminIsDeployUser";
206
+ }
207
+ };
208
+ /** No key logs the admin in, and nothing was done to make one. */
209
+ var ComposeServerAdminUnreachable = class extends GkmError {
210
+ target;
211
+ stderr;
212
+ constructor(target, stderr) {
213
+ super(`Could not log in as ${target} with a key (ssh said: ${stderr.trim() || "nothing"}). Check \`ssh ${target}\` works without a password — copy your key with \`ssh-copy-id ${target}\` — then run this again.`);
214
+ this.target = target;
215
+ this.stderr = stderr;
216
+ this.name = "ComposeServerAdminUnreachable";
217
+ }
218
+ };
219
+ /** `ssh-keygen` could not make the deploy key pair. */
220
+ var DeployKeyNotMade = class extends GkmError {
221
+ keyFile;
222
+ stderr;
223
+ constructor(keyFile, stderr) {
224
+ super(`Could not make the deploy key ${keyFile} (ssh-keygen said: ${stderr.trim() || "nothing"}). Pass another path with --key-file.`);
225
+ this.keyFile = keyFile;
226
+ this.stderr = stderr;
227
+ this.name = "DeployKeyNotMade";
228
+ }
229
+ };
230
+ /** The script on the server stopped before it finished. */
231
+ var ComposeServerSetupFailed = class extends GkmError {
232
+ target;
233
+ code;
234
+ constructor(target, code) {
235
+ super(`Setting up ${target} stopped (exit ${code}); its output is above. Fix what it names and run this again — every step it already finished is left as it is.`);
236
+ this.target = target;
237
+ this.code = code;
238
+ this.name = "ComposeServerSetupFailed";
239
+ }
240
+ };
241
+ /** The host key the network shows is not the one the server holds. */
242
+ var ComposeServerHostKeyMismatch = class extends GkmError {
243
+ host;
244
+ server;
245
+ scanned;
246
+ constructor(host, server, scanned) {
247
+ super(`${host}'s host key is ${server} on the server, but ${scanned || "nothing"} over the network. Something between here and the server answered for it, or the server is not the one you logged in to. Nothing was given to GitHub; find out why before running this again.`);
248
+ this.host = host;
249
+ this.server = server;
250
+ this.scanned = scanned;
251
+ this.name = "ComposeServerHostKeyMismatch";
252
+ }
253
+ };
254
+ /** The deploy key logged in, but cannot do what a deploy does. */
255
+ var ComposeServerCheckFailed = class extends GkmError {
256
+ target;
257
+ check;
258
+ output;
259
+ constructor(target, check, output) {
260
+ super(check === "docker" ? `The deploy key can't run docker as ${target} (ssh said: ${output.trim() || "nothing"}).` : `The deploy key can't open a tunnel as ${target} (got: ${output.trim() || "nothing"}). Check its line in the deploy user's authorized_keys says restrict,port-forwarding, and that sshd allows it forwarding.`);
261
+ this.target = target;
262
+ this.check = check;
263
+ this.output = output;
264
+ this.name = "ComposeServerCheckFailed";
265
+ }
266
+ };
267
+ /** `'…'`, for a value in a command line the remote shell reads. */
268
+ function shellQuote(value) {
269
+ return `'${value.replaceAll("'", `'\\''`)}'`;
270
+ }
271
+ /**
272
+ * The remote command that runs `script` with `args`: written to a temporary
273
+ * file (so the script keeps the terminal for any password it asks), run,
274
+ * and removed. `sudo` for everything but root.
275
+ */
276
+ function remoteCommand(script, args, sudo) {
277
+ return [
278
+ `f="$(mktemp)"`,
279
+ `echo ${Buffer.from(script).toString("base64")} | base64 -d > "$f"`,
280
+ `${sudo ? "sudo " : ""}bash "$f" ${args.map(shellQuote).join(" ")}; s=$?`,
281
+ `rm -f "$f"`,
282
+ "exit $s"
283
+ ].join("; ");
284
+ }
285
+ function sshOptions(server) {
286
+ return [
287
+ "-o",
288
+ "ConnectTimeout=20",
289
+ "-p",
290
+ String(server.port)
291
+ ];
292
+ }
293
+ /** `user@host`, as `ssh` takes it. */
294
+ function at(user, host) {
295
+ return `${user}@${host}`;
296
+ }
297
+ /** The real runner: the system's programs. */
298
+ const systemRunner = (command, args, options = {}) => new Promise((resolve, reject) => {
299
+ const child = spawn(command, args, {
300
+ stdio: [
301
+ options.interactive ? "inherit" : "pipe",
302
+ "pipe",
303
+ options.interactive ? "inherit" : "pipe"
304
+ ],
305
+ timeout: options.interactive ? void 0 : 6e4
306
+ });
307
+ let stdout = "";
308
+ let stderr = "";
309
+ child.stdout?.on("data", (chunk) => {
310
+ stdout += chunk.toString();
311
+ if (options.interactive) process.stdout.write(chunk);
312
+ });
313
+ child.stderr?.on("data", (chunk) => {
314
+ stderr += chunk.toString();
315
+ });
316
+ child.on("error", reject);
317
+ child.on("close", (code) => resolve({
318
+ code: code ?? 1,
319
+ stdout,
320
+ stderr
321
+ }));
322
+ if (child.stdin) child.stdin.end(options.input ?? "");
323
+ });
324
+ /** Whether `answer` is a yes, `fallback` when nothing was typed. */
325
+ function isYes(answer, fallback) {
326
+ const value = answer.trim().toLowerCase();
327
+ return value === "" ? fallback : value === "y" || value === "yes";
328
+ }
329
+ /** The SHA256 fingerprint of each key in `keys`, by `ssh-keygen -lf -`. */
330
+ async function fingerprints(run, keys) {
331
+ const { stdout } = await run("ssh-keygen", ["-lf", "-"], { input: keys });
332
+ return stdout.split("\n").map((line) => line.split(" ")[1]).filter((value) => Boolean(value));
333
+ }
334
+ /** The default deploy key pair for a stage. */
335
+ function defaultKeyFile(project, stage) {
336
+ return join(homedir(), ".ssh", `gkm-${project}-${stage}`);
337
+ }
338
+ /** `gkm compose:server`. */
339
+ async function composeServerCommand(options, deps = {}) {
340
+ const run = deps.run ?? systemRunner;
341
+ const gh = deps.gh ?? ghCli;
342
+ const ask = deps.ask ?? ((question) => prompt(question, { instead: "Name the server user with --admin and pass --yes." }));
343
+ const github = options.github !== false;
344
+ const { stage } = options;
345
+ const cwd = resolve(options.cwd ?? process.cwd());
346
+ const { workspace } = await loadWorkspaceConfig(cwd);
347
+ assertDeployedStage(workspace.stages, stage);
348
+ const server = composeServer({
349
+ stage,
350
+ local: false,
351
+ config: workspace.deploy?.compose?.server,
352
+ custom: (await (await secretsStoreFor(workspace, stage)).read(stage))?.custom
353
+ });
354
+ const admin = (options.admin ?? await ask(`The sudo user you log in to ${server.host} as (not root): `)).trim();
355
+ if (!admin || admin === "root") throw new ComposeServerAdminIsRoot();
356
+ if (admin === server.user) throw new ComposeServerAdminIsDeployUser(admin);
357
+ const keyFile = resolve(options.keyFile ?? defaultKeyFile(workspace.name, stage));
358
+ const comment = `gkm-${workspace.name}-${stage}-deploy`;
359
+ const repo = github ? options.repo ?? gh([
360
+ "repo",
361
+ "view",
362
+ "--json",
363
+ "nameWithOwner",
364
+ "-q",
365
+ ".nameWithOwner"
366
+ ]) : void 0;
367
+ const adminTarget = at(admin, server.host);
368
+ const deployTarget = at(server.user, server.host);
369
+ console.log(`\n🖥 Server for stage "${stage}"\n`);
370
+ console.log(` Server: ${server.host} (ssh port ${server.port})`);
371
+ console.log(` Admin: ${admin} — logs in with your key, runs sudo`);
372
+ console.log(` Deploy user: ${server.user} — docker group, no sudo, no password`);
373
+ console.log(` Deploy key: ${keyFile}${existsSync(keyFile) ? "" : " (new, made here)"}`);
374
+ console.log(` GitHub: ${repo ? `environment "${stage}" of ${repo}: DEPLOY_SSH_KEY, DEPLOY_KNOWN_HOSTS` : "left alone (--no-github)"}`);
375
+ console.log("\n On the server, through sudo:");
376
+ for (const step of [
377
+ "SSH: keys only, root's login off (and nothing else may turn passwords back on)",
378
+ `firewall: ${server.port}, 80 and 443 in, everything out`,
379
+ "security updates installed daily (unattended-upgrades); fail2ban on sshd",
380
+ "Docker and its compose plugin, from Docker's repository",
381
+ `user ${server.user}, the deploy key authorized with restrict,port-forwarding`
382
+ ]) console.log(` · ${step}`);
383
+ if (options.dryRun) {
384
+ console.log(`\n The script, run as: sudo bash setup.sh ${[
385
+ admin,
386
+ server.user,
387
+ String(server.port),
388
+ "<deploy key>",
389
+ comment
390
+ ].map(shellQuote).join(" ")}\n`);
391
+ console.log(SERVER_SCRIPT.replace(/^/gm, " "));
392
+ console.log(" --dry-run: nothing changed.\n");
393
+ return {
394
+ server,
395
+ admin,
396
+ keyFile,
397
+ ...repo ? { repo } : {}
398
+ };
399
+ }
400
+ if (!options.yes && !isYes(await ask(`\n Set up ${server.host}? [y/N] `), false)) {
401
+ console.log(" Nothing changed.\n");
402
+ return {
403
+ server,
404
+ admin,
405
+ keyFile,
406
+ ...repo ? { repo } : {}
407
+ };
408
+ }
409
+ if (!existsSync(keyFile)) {
410
+ await mkdir(dirname(keyFile), {
411
+ recursive: true,
412
+ mode: 448
413
+ });
414
+ const made = await run("ssh-keygen", [
415
+ "-t",
416
+ "ed25519",
417
+ "-N",
418
+ "",
419
+ "-C",
420
+ comment,
421
+ "-f",
422
+ keyFile
423
+ ]);
424
+ if (made.code !== 0) throw new DeployKeyNotMade(keyFile, made.stderr);
425
+ console.log(`\n ✓ Made the deploy key ${keyFile}`);
426
+ }
427
+ const publicKey = (await readFile(`${keyFile}.pub`, "utf-8")).trim();
428
+ const probe = (user) => run("ssh", [
429
+ "-o",
430
+ "BatchMode=yes",
431
+ "-o",
432
+ "StrictHostKeyChecking=accept-new",
433
+ ...sshOptions(server),
434
+ at(user, server.host),
435
+ "true"
436
+ ]);
437
+ let login = await probe(admin);
438
+ if (login.code !== 0) {
439
+ if ((await probe("root")).code === 0) {
440
+ if (isYes(await ask(`\n ${admin} can't log in with a key, but root can. Create ${admin} as a sudo user with root's keys? [Y/n] `), true)) await run("ssh", [
441
+ "-t",
442
+ ...sshOptions(server),
443
+ at("root", server.host),
444
+ remoteCommand(ADMIN_SCRIPT, [admin], false)
445
+ ], { interactive: true });
446
+ } else if (isYes(await ask(`\n ${admin} can't log in with a key. Copy yours there with ssh-copy-id (asks ${admin}'s password)? [Y/n] `), true)) await run("ssh-copy-id", [
447
+ "-p",
448
+ String(server.port),
449
+ adminTarget
450
+ ], { interactive: true });
451
+ login = await probe(admin);
452
+ if (login.code !== 0) throw new ComposeServerAdminUnreachable(adminTarget, login.stderr);
453
+ }
454
+ console.log(` ✓ ${adminTarget} logs in with a key\n`);
455
+ const setup = await run("ssh", [
456
+ "-t",
457
+ ...sshOptions(server),
458
+ adminTarget,
459
+ remoteCommand(SERVER_SCRIPT, [
460
+ admin,
461
+ server.user,
462
+ String(server.port),
463
+ publicKey,
464
+ comment
465
+ ], true)
466
+ ], { interactive: true });
467
+ if (setup.code !== 0) throw new ComposeServerSetupFailed(adminTarget, setup.code);
468
+ const serverFingerprint = setup.stdout.replaceAll("\r", "").match(/^HOSTKEY=(\S+)$/m)?.[1];
469
+ if (!serverFingerprint) throw new ComposeServerSetupFailed(adminTarget, setup.code);
470
+ const knownHosts = (await run("ssh-keyscan", [
471
+ "-t",
472
+ "ed25519",
473
+ "-p",
474
+ String(server.port),
475
+ server.host
476
+ ])).stdout.split("\n").filter((line) => line.trim() && !line.startsWith("#")).join("\n");
477
+ const [scanned = ""] = await fingerprints(run, knownHosts);
478
+ if (scanned !== serverFingerprint) throw new ComposeServerHostKeyMismatch(server.host, serverFingerprint, scanned);
479
+ console.log(`\n ✓ Host key ${scanned}, as the server reports it`);
480
+ if (repo) {
481
+ gh([
482
+ "api",
483
+ "--method",
484
+ "PUT",
485
+ `repos/${repo}/environments/${stage}`
486
+ ]);
487
+ gh([
488
+ "variable",
489
+ "set",
490
+ "DEPLOY_KNOWN_HOSTS",
491
+ "--env",
492
+ stage,
493
+ "--repo",
494
+ repo,
495
+ "--body",
496
+ knownHosts
497
+ ]);
498
+ gh([
499
+ "secret",
500
+ "set",
501
+ "DEPLOY_SSH_KEY",
502
+ "--env",
503
+ stage,
504
+ "--repo",
505
+ repo
506
+ ], await readFile(keyFile, "utf-8"));
507
+ console.log(` ✓ GitHub: environment "${stage}", DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS`);
508
+ }
509
+ const known = join(dirname(keyFile), `.gkm-known-${workspace.name}-${stage}`);
510
+ await writeFile(known, `${knownHosts}\n`);
511
+ try {
512
+ const asCi = [
513
+ "-i",
514
+ keyFile,
515
+ "-o",
516
+ "IdentitiesOnly=yes",
517
+ "-o",
518
+ "BatchMode=yes",
519
+ "-o",
520
+ `UserKnownHostsFile=${known}`,
521
+ "-o",
522
+ "StrictHostKeyChecking=yes",
523
+ ...sshOptions(server)
524
+ ];
525
+ const docker = await run("ssh", [
526
+ ...asCi,
527
+ deployTarget,
528
+ "docker",
529
+ "version",
530
+ "--format",
531
+ "{{.Server.Version}}"
532
+ ]);
533
+ if (docker.code !== 0) throw new ComposeServerCheckFailed(deployTarget, "docker", docker.stderr);
534
+ console.log(` ✓ ${deployTarget} runs docker (engine ${docker.stdout.trim()})`);
535
+ const tunnel = await run("ssh", [
536
+ ...asCi,
537
+ "-W",
538
+ `127.0.0.1:${server.port}`,
539
+ deployTarget
540
+ ]);
541
+ if (!tunnel.stdout.startsWith("SSH-2.0")) throw new ComposeServerCheckFailed(deployTarget, "tunnel", tunnel.stdout.slice(0, 80) || tunnel.stderr);
542
+ console.log(` ✓ ${deployTarget} opens tunnels (migrations)`);
543
+ } finally {
544
+ await rm(known, { force: true });
545
+ }
546
+ console.log(`\n✅ ${server.host} is ready for "${stage}".${repo ? " CI deploys it with the key it was given." : ""} To deploy from here, load the key first: ssh-add ${keyFile}\n`);
547
+ return {
548
+ server,
549
+ admin,
550
+ keyFile,
551
+ knownHosts,
552
+ ...repo ? { repo } : {}
553
+ };
554
+ }
555
+ //#endregion
556
+ export { composeServerCommand };
557
+
558
+ //# sourceMappingURL=serverSetup--O61SRvg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverSetup--O61SRvg.mjs","names":[],"sources":["../src/compose/serverScript.ts","../src/compose/serverSetup.ts"],"sourcesContent":["/**\n * What `gkm compose:server` runs on the server, as root (through the admin\n * user's sudo). Plain bash, so `--dry-run` can print exactly what will run,\n * and safe to run again: every step changes only what is missing or wrong.\n *\n * Arguments, in order: the admin user (the one running sudo), the deploy\n * user, the SSH port, the deploy key's public line, and its comment.\n *\n * The last line it prints is `HOSTKEY=<fingerprint>` — the server's own\n * ed25519 host key, which the command checks the network's against before\n * pinning it for CI.\n */\nexport const SERVER_SCRIPT = String.raw`set -euo pipefail\nexport DEBIAN_FRONTEND=noninteractive\nADMIN=\"$1\"; DEPLOY=\"$2\"; SSH_PORT=\"$3\"; PUB=\"$4\"; COMMENT=\"$5\"\nsay() { echo \" $*\"; }\nfail() { echo \" ✗ $*\" >&2; exit 1; }\n\n. /etc/os-release\ncase \"$ID\" in\n\tubuntu | debian) ;;\n\t*) fail \"gkm sets up Ubuntu and Debian servers; this one is $ID.\" ;;\nesac\n\n# ── SSH: keys only, no root ────────────────────────────────────────────────\n# Before password logins are turned off, the admin must have a key to come\n# back with — otherwise this would lock them out.\nADMIN_HOME=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\n[ -s \"$ADMIN_HOME/.ssh/authorized_keys\" ] ||\n\tfail \"$ADMIN has no key in $ADMIN_HOME/.ssh/authorized_keys; turning off password logins would lock them out.\"\n# First match wins in sshd_config, and 00- sorts before what a provider ships\n# (cloud-init's 50-cloud-init.conf turns password logins back on).\ncat > /etc/ssh/sshd_config.d/00-gkm-hardening.conf <<'EOF'\n# Written by gkm compose:server.\nPermitRootLogin no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nEOF\n# The deploy migrates through an SSH tunnel to the server's loopback.\ncat > /etc/ssh/sshd_config.d/60-gkm-deploy.conf <<EOF\n# Written by gkm compose:server.\nMatch User $DEPLOY\n AllowTcpForwarding local\nEOF\nsshd -t\nsystemctl reload ssh 2>/dev/null || systemctl reload sshd\n# What sshd actually does now, whatever else is in its config.\nEFFECTIVE=\"$(sshd -T)\"\nfor setting in 'permitrootlogin no' 'passwordauthentication no' 'kbdinteractiveauthentication no'; do\n\tgrep -qx \"$setting\" <<<\"$EFFECTIVE\" || fail \"sshd still does not say '$setting'; another file in /etc/ssh overrides it.\"\ndone\nFORWARD=\"$(sshd -T -C \"user=$DEPLOY,host=localhost,addr=127.0.0.1\" | sed -n 's/^allowtcpforwarding //p')\"\ncase \"$FORWARD\" in\n\tyes | all | local) ;;\n\t*) fail \"sshd does not let $DEPLOY forward ports (allowtcpforwarding $FORWARD).\" ;;\nesac\nsay \"sshd: keys only, no root login; $DEPLOY may open local tunnels\"\n\n# ── Firewall: SSH, HTTP, HTTPS ─────────────────────────────────────────────\ncommand -v ufw >/dev/null || { apt-get update -qq && apt-get install -y -qq ufw >/dev/null; }\nufw default deny incoming >/dev/null\nufw default allow outgoing >/dev/null\nufw allow \"$SSH_PORT/tcp\" >/dev/null\nufw allow 80/tcp >/dev/null\nufw allow 443/tcp >/dev/null\nufw --force enable >/dev/null\nsay \"firewall: $SSH_PORT, 80, 443 in; everything out\"\nEXTRA=\"$(ufw status | awk 'NR > 4 && $1 != \"\" { print $1 }' | grep -vxE \"(($SSH_PORT|80|443)(/tcp)?|OpenSSH)\" | sort -u || true)\"\nif [ -n \"$EXTRA\" ]; then\n\tsay \"⚠ also open: $(echo $EXTRA). gkm uses none of them; close each with: sudo ufw delete allow <port>\"\nfi\n\n# ── Updates and bans ───────────────────────────────────────────────────────\napt-get update -qq\napt-get install -y -qq unattended-upgrades fail2ban >/dev/null\ncat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'\nAPT::Periodic::Update-Package-Lists \"1\";\nAPT::Periodic::Unattended-Upgrade \"1\";\nEOF\ncat > /etc/fail2ban/jail.d/gkm.local <<EOF\n# Written by gkm compose:server.\n[sshd]\nenabled = true\nport = $SSH_PORT\nEOF\nsystemctl enable --now unattended-upgrades fail2ban >/dev/null 2>&1\nsystemctl restart fail2ban\nsay \"security updates install daily; fail2ban watches sshd\"\n\n# ── Docker, from Docker's own repository ───────────────────────────────────\nif ! command -v docker >/dev/null || ! docker compose version >/dev/null 2>&1; then\n\tsay \"installing Docker…\"\n\tapt-get install -y -qq ca-certificates curl >/dev/null\n\tinstall -m 0755 -d /etc/apt/keyrings\n\tcurl -fsSL \"https://download.docker.com/linux/$ID/gpg\" -o /etc/apt/keyrings/docker.asc\n\tchmod a+r /etc/apt/keyrings/docker.asc\n\techo \"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable\" \\\n\t\t> /etc/apt/sources.list.d/docker.list\n\tapt-get update -qq\n\tapt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/dev/null\nfi\nsystemctl enable --now docker >/dev/null 2>&1\nsay \"docker $(docker version --format '{{.Server.Version}}')\"\n\n# ── The deploy user: no password, no sudo, in the docker group ─────────────\nid \"$DEPLOY\" >/dev/null 2>&1 || adduser --disabled-password --gecos \"\" \"$DEPLOY\" >/dev/null\nusermod -aG docker \"$DEPLOY\"\nDEPLOY_HOME=\"$(getent passwd \"$DEPLOY\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$DEPLOY\" -g \"$DEPLOY\" \"$DEPLOY_HOME/.ssh\"\nAUTH=\"$DEPLOY_HOME/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# One managed line: this key (or an earlier one by the same name) replaced,\n# with nothing allowed but the commands and the tunnel the deploy uses.\nKEYBODY=\"$(awk '{ print $2 }' <<<\"$PUB\")\"\ngrep -v -F -e \"$KEYBODY\" -e \" $COMMENT\" \"$AUTH\" > \"$AUTH.new\" || true\necho \"restrict,port-forwarding $PUB\" >> \"$AUTH.new\"\nmv \"$AUTH.new\" \"$AUTH\"\nchown \"$DEPLOY:$DEPLOY\" \"$AUTH\"\nchmod 600 \"$AUTH\"\nsay \"user $DEPLOY (docker group), deploy key authorized with restrict,port-forwarding\"\nOTHERS=\"$(grep -v -F -e \"$KEYBODY\" \"$AUTH\" | grep -c . || true)\"\nif [ \"$OTHERS\" -gt 0 ]; then\n\tsay \"⚠ $AUTH holds $OTHERS other key(s). Review: sudo cat $AUTH\"\nfi\n\necho \"HOSTKEY=$(ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub | awk '{ print $2 }')\"\n`;\n\n/**\n * What runs as root to give a fresh server its admin — the guide's first\n * step, for a server only root can log in to yet: a sudo user, with root's\n * keys so the same key logs in. `adduser` asks for its password, which sudo\n * will ask for.\n */\nexport const ADMIN_SCRIPT = `set -euo pipefail\nADMIN=\"$1\"\nif ! id \"$ADMIN\" >/dev/null 2>&1; then\n\techo \" creating $ADMIN — choose the password sudo will ask for:\"\n\tadduser --gecos \"\" \"$ADMIN\"\nfi\nusermod -aG sudo \"$ADMIN\"\nHOME_DIR=\"$(getent passwd \"$ADMIN\" | cut -d: -f6)\"\ninstall -d -m 700 -o \"$ADMIN\" -g \"$ADMIN\" \"$HOME_DIR/.ssh\"\nAUTH=\"$HOME_DIR/.ssh/authorized_keys\"\ntouch \"$AUTH\"\n# The keys alone: a provider's options on root's lines (a command=\"…\" that\n# says \"log in as ubuntu\") would stop the admin's login too.\n{ grep -oE '(ssh|ecdsa|sk)-[^ ]+ [A-Za-z0-9+/=]+( .*)?$' /root/.ssh/authorized_keys || true; } |\n\twhile IFS= read -r key; do\n\t\tgrep -qxF \"$key\" \"$AUTH\" || echo \"$key\" >> \"$AUTH\"\n\tdone\nchown \"$ADMIN:$ADMIN\" \"$AUTH\"\nchmod 600 \"$AUTH\"\necho \" $ADMIN is a sudo user, with root's SSH keys\"\n`;\n","/**\n * `gkm compose:server` — make a VPS ready for a stage's compose deploys, from\n * this machine, in one go.\n *\n * It logs in as the server's admin — a sudo user, never root — and, through\n * sudo, sets the server up the way a production VPS should be: SSH by key\n * only with root's login off, a firewall open on SSH, 80 and 443 alone,\n * security updates installed daily, fail2ban on sshd, and Docker from\n * Docker's own repository. It then creates the stage's deploy user (in the\n * docker group, no sudo, no password) and authorizes a deploy key on it that\n * may run commands and open the tunnel migrations use, nothing more.\n *\n * Off the server: it makes the deploy key pair here, pins the server's host\n * key — checked against the fingerprint the server reports of itself — and\n * gives both to the stage's GitHub environment as `DEPLOY_SSH_KEY` and\n * `DEPLOY_KNOWN_HOSTS`, which the generated deploy workflow reads. Last, it\n * logs in exactly as CI will, and checks Docker and the tunnel answer.\n *\n * A fresh server only root can log in to gets its admin first: with root's\n * key it creates the user, or with the admin's password it copies a key in.\n * Safe to run again: each step changes only what is missing or wrong.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { loadWorkspaceConfig } from '../config';\nimport { type Gh, ghCli } from '../deploy/github';\nimport { GkmError } from '../errors';\nimport { prompt } from '../prompt';\nimport { secretsStoreFor } from '../secrets/store.js';\nimport { assertDeployedStage } from '../workspace/stages.js';\nimport { type ComposeServer, composeServer } from './server';\nimport { ADMIN_SCRIPT, SERVER_SCRIPT } from './serverScript';\n\nexport interface ComposeServerSetupOptions {\n\t/** The deployed stage whose server this is. */\n\tstage: string;\n\t/** The server's sudo user. Asked for when absent. */\n\tadmin?: string;\n\t/** The deploy key pair. Default `~/.ssh/gkm-<project>-<stage>`. */\n\tkeyFile?: string;\n\t/** `owner/name`; defaults to the repository `gh` sees here. */\n\trepo?: string;\n\t/** `--no-github`: leave the GitHub environment alone. */\n\tgithub?: boolean;\n\t/** Print the plan and the script; connect to nothing. */\n\tdryRun?: boolean;\n\t/** Apply without asking first. */\n\tyes?: boolean;\n\tcwd?: string;\n}\n\n/** What a finished command ran: output kept, its exit code. */\nexport interface Ran {\n\tcode: number;\n\tstdout: string;\n\tstderr: string;\n}\n\n/**\n * Runs a program. `interactive` gives it this terminal's stdin and stderr —\n * for a password sudo or adduser asks — while stdout is still kept, and\n * echoed as it comes.\n */\nexport type Runner = (\n\tcommand: string,\n\targs: readonly string[],\n\toptions?: { input?: string; interactive?: boolean },\n) => Promise<Ran>;\n\nexport interface ComposeServerSetupDeps {\n\trun: Runner;\n\tgh: Gh;\n\t/** Ask the person at the terminal. */\n\task: (question: string) => Promise<string>;\n}\n\nexport interface ComposeServerSetupResult {\n\tserver: ComposeServer;\n\tadmin: string;\n\tkeyFile: string;\n\t/** The pinned host key line, as `known_hosts` holds it. Absent on a dry run. */\n\tknownHosts?: string;\n\t/** The repository whose environment was given the key. */\n\trepo?: string;\n}\n\n/** The admin named is root, whose login this command turns off. */\nexport class ComposeServerAdminIsRoot extends GkmError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t\"The admin can't be root: setting up the server turns root's SSH login \" +\n\t\t\t\t'off. Name the sudo user you log in as (--admin <user>). A fresh ' +\n\t\t\t\t'server with only root gets one: run this again with the name it ' +\n\t\t\t\t\"should have, and gkm offers to create it with root's key.\",\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsRoot';\n\t}\n}\n\n/** The admin named is the deploy user, which has no sudo. */\nexport class ComposeServerAdminIsDeployUser extends GkmError {\n\tconstructor(readonly user: string) {\n\t\tsuper(\n\t\t\t`'${user}' is the stage's deploy user (deploy.compose.server), which ` +\n\t\t\t\t'gkm creates without sudo. Name the sudo user you log in as with --admin.',\n\t\t);\n\t\tthis.name = 'ComposeServerAdminIsDeployUser';\n\t}\n}\n\n/** No key logs the admin in, and nothing was done to make one. */\nexport class ComposeServerAdminUnreachable extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not log in as ${target} with a key (ssh said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t`Check \\`ssh ${target}\\` works without a password — copy your key with ` +\n\t\t\t\t`\\`ssh-copy-id ${target}\\` — then run this again.`,\n\t\t);\n\t\tthis.name = 'ComposeServerAdminUnreachable';\n\t}\n}\n\n/** `ssh-keygen` could not make the deploy key pair. */\nexport class DeployKeyNotMade extends GkmError {\n\tconstructor(\n\t\treadonly keyFile: string,\n\t\treadonly stderr: string,\n\t) {\n\t\tsuper(\n\t\t\t`Could not make the deploy key ${keyFile} (ssh-keygen said: ${stderr.trim() || 'nothing'}). ` +\n\t\t\t\t'Pass another path with --key-file.',\n\t\t);\n\t\tthis.name = 'DeployKeyNotMade';\n\t}\n}\n\n/** The script on the server stopped before it finished. */\nexport class ComposeServerSetupFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly code: number,\n\t) {\n\t\tsuper(\n\t\t\t`Setting up ${target} stopped (exit ${code}); its output is above. ` +\n\t\t\t\t'Fix what it names and run this again — every step it already ' +\n\t\t\t\t'finished is left as it is.',\n\t\t);\n\t\tthis.name = 'ComposeServerSetupFailed';\n\t}\n}\n\n/** The host key the network shows is not the one the server holds. */\nexport class ComposeServerHostKeyMismatch extends GkmError {\n\tconstructor(\n\t\treadonly host: string,\n\t\treadonly server: string,\n\t\treadonly scanned: string,\n\t) {\n\t\tsuper(\n\t\t\t`${host}'s host key is ${server} on the server, but ${scanned || 'nothing'} ` +\n\t\t\t\t'over the network. Something between here and the server answered for ' +\n\t\t\t\t'it, or the server is not the one you logged in to. Nothing was given ' +\n\t\t\t\t'to GitHub; find out why before running this again.',\n\t\t);\n\t\tthis.name = 'ComposeServerHostKeyMismatch';\n\t}\n}\n\n/** The deploy key logged in, but cannot do what a deploy does. */\nexport class ComposeServerCheckFailed extends GkmError {\n\tconstructor(\n\t\treadonly target: string,\n\t\treadonly check: 'docker' | 'tunnel',\n\t\treadonly output: string,\n\t) {\n\t\tsuper(\n\t\t\tcheck === 'docker'\n\t\t\t\t? `The deploy key can't run docker as ${target} (ssh said: ${output.trim() || 'nothing'}).`\n\t\t\t\t: `The deploy key can't open a tunnel as ${target} (got: ${output.trim() || 'nothing'}). ` +\n\t\t\t\t\t\t\"Check its line in the deploy user's authorized_keys says \" +\n\t\t\t\t\t\t'restrict,port-forwarding, and that sshd allows it forwarding.',\n\t\t);\n\t\tthis.name = 'ComposeServerCheckFailed';\n\t}\n}\n\n/** `'…'`, for a value in a command line the remote shell reads. */\nfunction shellQuote(value: string): string {\n\treturn `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/**\n * The remote command that runs `script` with `args`: written to a temporary\n * file (so the script keeps the terminal for any password it asks), run,\n * and removed. `sudo` for everything but root.\n */\nexport function remoteCommand(\n\tscript: string,\n\targs: readonly string[],\n\tsudo: boolean,\n): string {\n\tconst encoded = Buffer.from(script).toString('base64');\n\treturn [\n\t\t`f=\"$(mktemp)\"`,\n\t\t`echo ${encoded} | base64 -d > \"$f\"`,\n\t\t`${sudo ? 'sudo ' : ''}bash \"$f\" ${args.map(shellQuote).join(' ')}; s=$?`,\n\t\t`rm -f \"$f\"`,\n\t\t'exit $s',\n\t].join('; ');\n}\n\nfunction sshOptions(server: ComposeServer): string[] {\n\treturn ['-o', 'ConnectTimeout=20', '-p', String(server.port)];\n}\n\n/** `user@host`, as `ssh` takes it. */\nfunction at(user: string, host: string): string {\n\treturn `${user}@${host}`;\n}\n\n/** The real runner: the system's programs. */\nexport const systemRunner: Runner = (command, args, options = {}) =>\n\tnew Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tstdio: [\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t\t'pipe',\n\t\t\t\toptions.interactive ? 'inherit' : 'pipe',\n\t\t\t],\n\t\t\ttimeout: options.interactive ? undefined : 60_000,\n\t\t});\n\t\tlet stdout = '';\n\t\tlet stderr = '';\n\t\tchild.stdout?.on('data', (chunk: Buffer) => {\n\t\t\tstdout += chunk.toString();\n\t\t\tif (options.interactive) process.stdout.write(chunk);\n\t\t});\n\t\tchild.stderr?.on('data', (chunk: Buffer) => {\n\t\t\tstderr += chunk.toString();\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n\t\tif (child.stdin) child.stdin.end(options.input ?? '');\n\t});\n\n/** Whether `answer` is a yes, `fallback` when nothing was typed. */\nfunction isYes(answer: string, fallback: boolean): boolean {\n\tconst value = answer.trim().toLowerCase();\n\treturn value === '' ? fallback : value === 'y' || value === 'yes';\n}\n\n/** The SHA256 fingerprint of each key in `keys`, by `ssh-keygen -lf -`. */\nasync function fingerprints(run: Runner, keys: string): Promise<string[]> {\n\tconst { stdout } = await run('ssh-keygen', ['-lf', '-'], { input: keys });\n\treturn stdout\n\t\t.split('\\n')\n\t\t.map((line) => line.split(' ')[1])\n\t\t.filter((value): value is string => Boolean(value));\n}\n\n/** The default deploy key pair for a stage. */\nexport function defaultKeyFile(project: string, stage: string): string {\n\treturn join(homedir(), '.ssh', `gkm-${project}-${stage}`);\n}\n\n/** `gkm compose:server`. */\nexport async function composeServerCommand(\n\toptions: ComposeServerSetupOptions,\n\tdeps: Partial<ComposeServerSetupDeps> = {},\n): Promise<ComposeServerSetupResult> {\n\tconst run = deps.run ?? systemRunner;\n\tconst gh = deps.gh ?? ghCli;\n\tconst ask =\n\t\tdeps.ask ??\n\t\t((question: string) =>\n\t\t\tprompt(question, {\n\t\t\t\tinstead: 'Name the server user with --admin and pass --yes.',\n\t\t\t}));\n\tconst github = options.github !== false;\n\tconst { stage } = options;\n\n\tconst cwd = resolve(options.cwd ?? process.cwd());\n\tconst { workspace } = await loadWorkspaceConfig(cwd);\n\tassertDeployedStage(workspace.stages, stage);\n\tconst server = composeServer({\n\t\tstage,\n\t\tlocal: false,\n\t\tconfig: workspace.deploy?.compose?.server,\n\t\tcustom: (await (await secretsStoreFor(workspace, stage)).read(stage))\n\t\t\t?.custom,\n\t})!;\n\n\tconst admin = (\n\t\toptions.admin ??\n\t\t(await ask(`The sudo user you log in to ${server.host} as (not root): `))\n\t).trim();\n\tif (!admin || admin === 'root') throw new ComposeServerAdminIsRoot();\n\tif (admin === server.user) throw new ComposeServerAdminIsDeployUser(admin);\n\n\tconst keyFile = resolve(\n\t\toptions.keyFile ?? defaultKeyFile(workspace.name, stage),\n\t);\n\tconst comment = `gkm-${workspace.name}-${stage}-deploy`;\n\tconst repo = github\n\t\t? (options.repo ??\n\t\t\tgh(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']))\n\t\t: undefined;\n\tconst adminTarget = at(admin, server.host);\n\tconst deployTarget = at(server.user, server.host);\n\n\tconsole.log(`\\n🖥 Server for stage \"${stage}\"\\n`);\n\tconsole.log(` Server: ${server.host} (ssh port ${server.port})`);\n\tconsole.log(` Admin: ${admin} — logs in with your key, runs sudo`);\n\tconsole.log(\n\t\t` Deploy user: ${server.user} — docker group, no sudo, no password`,\n\t);\n\tconsole.log(\n\t\t` Deploy key: ${keyFile}${existsSync(keyFile) ? '' : ' (new, made here)'}`,\n\t);\n\tconsole.log(\n\t\t` GitHub: ${repo ? `environment \"${stage}\" of ${repo}: DEPLOY_SSH_KEY, DEPLOY_KNOWN_HOSTS` : 'left alone (--no-github)'}`,\n\t);\n\tconsole.log('\\n On the server, through sudo:');\n\tfor (const step of [\n\t\t\"SSH: keys only, root's login off (and nothing else may turn passwords back on)\",\n\t\t`firewall: ${server.port}, 80 and 443 in, everything out`,\n\t\t'security updates installed daily (unattended-upgrades); fail2ban on sshd',\n\t\t\"Docker and its compose plugin, from Docker's repository\",\n\t\t`user ${server.user}, the deploy key authorized with restrict,port-forwarding`,\n\t]) {\n\t\tconsole.log(` · ${step}`);\n\t}\n\n\tif (options.dryRun) {\n\t\tconsole.log(\n\t\t\t`\\n The script, run as: sudo bash setup.sh ${[admin, server.user, String(server.port), '<deploy key>', comment].map(shellQuote).join(' ')}\\n`,\n\t\t);\n\t\tconsole.log(SERVER_SCRIPT.replace(/^/gm, ' '));\n\t\tconsole.log(' --dry-run: nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\tif (\n\t\t!options.yes &&\n\t\t!isYes(await ask(`\\n Set up ${server.host}? [y/N] `), false)\n\t) {\n\t\tconsole.log(' Nothing changed.\\n');\n\t\treturn { server, admin, keyFile, ...(repo ? { repo } : {}) };\n\t}\n\n\t// ── The deploy key pair, here ──────────────────────────────────────────\n\tif (!existsSync(keyFile)) {\n\t\tawait mkdir(dirname(keyFile), { recursive: true, mode: 0o700 });\n\t\tconst made = await run('ssh-keygen', [\n\t\t\t'-t',\n\t\t\t'ed25519',\n\t\t\t'-N',\n\t\t\t'',\n\t\t\t'-C',\n\t\t\tcomment,\n\t\t\t'-f',\n\t\t\tkeyFile,\n\t\t]);\n\t\tif (made.code !== 0) throw new DeployKeyNotMade(keyFile, made.stderr);\n\t\tconsole.log(`\\n ✓ Made the deploy key ${keyFile}`);\n\t}\n\tconst publicKey = (await readFile(`${keyFile}.pub`, 'utf-8')).trim();\n\n\t// ── The admin's login ──────────────────────────────────────────────────\n\t// Key only, and the host key accepted on first sight — as the first\n\t// `ssh` to a new server does. CI's is pinned and checked below.\n\tconst probe = (user: string) =>\n\t\trun('ssh', [\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=accept-new',\n\t\t\t...sshOptions(server),\n\t\t\tat(user, server.host),\n\t\t\t'true',\n\t\t]);\n\tlet login = await probe(admin);\n\tif (login.code !== 0) {\n\t\tconst root = await probe('root');\n\t\tif (root.code === 0) {\n\t\t\tif (\n\t\t\t\tisYes(\n\t\t\t\t\tawait ask(\n\t\t\t\t\t\t`\\n ${admin} can't log in with a key, but root can. Create ${admin} as a sudo user with root's keys? [Y/n] `,\n\t\t\t\t\t),\n\t\t\t\t\ttrue,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tawait run(\n\t\t\t\t\t'ssh',\n\t\t\t\t\t[\n\t\t\t\t\t\t'-t',\n\t\t\t\t\t\t...sshOptions(server),\n\t\t\t\t\t\tat('root', server.host),\n\t\t\t\t\t\tremoteCommand(ADMIN_SCRIPT, [admin], false),\n\t\t\t\t\t],\n\t\t\t\t\t{ interactive: true },\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (\n\t\t\tisYes(\n\t\t\t\tawait ask(\n\t\t\t\t\t`\\n ${admin} can't log in with a key. Copy yours there with ssh-copy-id (asks ${admin}'s password)? [Y/n] `,\n\t\t\t\t),\n\t\t\t\ttrue,\n\t\t\t)\n\t\t) {\n\t\t\tawait run('ssh-copy-id', ['-p', String(server.port), adminTarget], {\n\t\t\t\tinteractive: true,\n\t\t\t});\n\t\t}\n\t\tlogin = await probe(admin);\n\t\tif (login.code !== 0) {\n\t\t\tthrow new ComposeServerAdminUnreachable(adminTarget, login.stderr);\n\t\t}\n\t}\n\tconsole.log(` ✓ ${adminTarget} logs in with a key\\n`);\n\n\t// ── The server ─────────────────────────────────────────────────────────\n\tconst setup = await run(\n\t\t'ssh',\n\t\t[\n\t\t\t'-t',\n\t\t\t...sshOptions(server),\n\t\t\tadminTarget,\n\t\t\tremoteCommand(\n\t\t\t\tSERVER_SCRIPT,\n\t\t\t\t[admin, server.user, String(server.port), publicKey, comment],\n\t\t\t\ttrue,\n\t\t\t),\n\t\t],\n\t\t{ interactive: true },\n\t);\n\tif (setup.code !== 0) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\tconst serverFingerprint = setup.stdout\n\t\t.replaceAll('\\r', '')\n\t\t.match(/^HOSTKEY=(\\S+)$/m)?.[1];\n\tif (!serverFingerprint) {\n\t\tthrow new ComposeServerSetupFailed(adminTarget, setup.code);\n\t}\n\n\t// ── The host key, pinned ───────────────────────────────────────────────\n\tconst scan = await run('ssh-keyscan', [\n\t\t'-t',\n\t\t'ed25519',\n\t\t'-p',\n\t\tString(server.port),\n\t\tserver.host,\n\t]);\n\tconst knownHosts = scan.stdout\n\t\t.split('\\n')\n\t\t.filter((line) => line.trim() && !line.startsWith('#'))\n\t\t.join('\\n');\n\tconst [scanned = ''] = await fingerprints(run, knownHosts);\n\tif (scanned !== serverFingerprint) {\n\t\tthrow new ComposeServerHostKeyMismatch(\n\t\t\tserver.host,\n\t\t\tserverFingerprint,\n\t\t\tscanned,\n\t\t);\n\t}\n\tconsole.log(`\\n ✓ Host key ${scanned}, as the server reports it`);\n\n\tif (repo) {\n\t\tgh(['api', '--method', 'PUT', `repos/${repo}/environments/${stage}`]);\n\t\tgh([\n\t\t\t'variable',\n\t\t\t'set',\n\t\t\t'DEPLOY_KNOWN_HOSTS',\n\t\t\t'--env',\n\t\t\tstage,\n\t\t\t'--repo',\n\t\t\trepo,\n\t\t\t'--body',\n\t\t\tknownHosts,\n\t\t]);\n\t\t// Through stdin, so the key is never an argument a process list shows.\n\t\tgh(\n\t\t\t['secret', 'set', 'DEPLOY_SSH_KEY', '--env', stage, '--repo', repo],\n\t\t\tawait readFile(keyFile, 'utf-8'),\n\t\t);\n\t\tconsole.log(\n\t\t\t` ✓ GitHub: environment \"${stage}\", DEPLOY_SSH_KEY and DEPLOY_KNOWN_HOSTS`,\n\t\t);\n\t}\n\n\t// ── Logged in as CI will be ────────────────────────────────────────────\n\tconst known = join(dirname(keyFile), `.gkm-known-${workspace.name}-${stage}`);\n\tawait writeFile(known, `${knownHosts}\\n`);\n\ttry {\n\t\tconst asCi = [\n\t\t\t'-i',\n\t\t\tkeyFile,\n\t\t\t'-o',\n\t\t\t'IdentitiesOnly=yes',\n\t\t\t'-o',\n\t\t\t'BatchMode=yes',\n\t\t\t'-o',\n\t\t\t`UserKnownHostsFile=${known}`,\n\t\t\t'-o',\n\t\t\t'StrictHostKeyChecking=yes',\n\t\t\t...sshOptions(server),\n\t\t];\n\t\tconst docker = await run('ssh', [\n\t\t\t...asCi,\n\t\t\tdeployTarget,\n\t\t\t'docker',\n\t\t\t'version',\n\t\t\t'--format',\n\t\t\t'{{.Server.Version}}',\n\t\t]);\n\t\tif (docker.code !== 0) {\n\t\t\tthrow new ComposeServerCheckFailed(deployTarget, 'docker', docker.stderr);\n\t\t}\n\t\tconsole.log(\n\t\t\t` ✓ ${deployTarget} runs docker (engine ${docker.stdout.trim()})`,\n\t\t);\n\t\t// The server's own sshd, through a tunnel: what a migration does to\n\t\t// reach Postgres on the server's loopback.\n\t\tconst tunnel = await run('ssh', [\n\t\t\t...asCi,\n\t\t\t'-W',\n\t\t\t`127.0.0.1:${server.port}`,\n\t\t\tdeployTarget,\n\t\t]);\n\t\tif (!tunnel.stdout.startsWith('SSH-2.0')) {\n\t\t\tthrow new ComposeServerCheckFailed(\n\t\t\t\tdeployTarget,\n\t\t\t\t'tunnel',\n\t\t\t\ttunnel.stdout.slice(0, 80) || tunnel.stderr,\n\t\t\t);\n\t\t}\n\t\tconsole.log(` ✓ ${deployTarget} opens tunnels (migrations)`);\n\t} finally {\n\t\tawait rm(known, { force: true });\n\t}\n\n\tconsole.log(\n\t\t`\\n✅ ${server.host} is ready for \"${stage}\".${repo ? ' CI deploys it with the key it was given.' : ''} ` +\n\t\t\t`To deploy from here, load the key first: ssh-add ${keyFile}\\n`,\n\t);\n\treturn {\n\t\tserver,\n\t\tadmin,\n\t\tkeyFile,\n\t\tknownHosts,\n\t\t...(repo ? { repo } : {}),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAa,gBAAgB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HvC,MAAa,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;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