@trojeancedric/deployer 0.1.0 → 0.1.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 (3) hide show
  1. package/README.md +30 -3
  2. package/dist/deployer.js +867 -18
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -25,7 +25,14 @@ deployer # interactive UI → Build & push
25
25
  deployer build # builds every default image, tags <version>-<sha8> + latest, pushes
26
26
  ```
27
27
 
28
- **2. On the server**, in the directory holding your `docker-compose.yml` and `.env`:
28
+ **2. Connect the server** — from the same repository:
29
+
30
+ ```bash
31
+ deployer setup # guided: repo, server, ssh, deployer + docker there, a read-only registry token
32
+ deployer build --deploy
33
+ ```
34
+
35
+ **Or by hand, on the server**, in the directory holding your `docker-compose.yml` and `.env`:
29
36
 
30
37
  ```bash
31
38
  echo "$GHCR_TOKEN" | docker login ghcr.io -u <github-user> --password-stdin # token with read:packages
@@ -37,6 +44,23 @@ deployer deploy latest --yes
37
44
 
38
45
  Copy `deployer.json` to the server once with `deployer sync` (see *remote* below), or by hand.
39
46
 
47
+ ## Setting up a server: `deployer setup`
48
+
49
+ An interactive walk-through, run on your build machine. Run it again whenever something changes — the current values are the defaults.
50
+
51
+ 1. **Project** — finds `deployer.json` (or creates it like `deployer init`) and asks for the GitHub repository (`owner/name`, default: the `origin` remote).
52
+ 2. **Server** — host, ssh port and user, and how you log in: your usual ssh login, a key file, or a **password**. With a password, deployer creates a dedicated key (`~/.ssh/deployer_<project>`) and installs it with `ssh-copy-id`, which asks for the password once — deploys run ssh without prompts, so they need a key. It then connects (offering to trust a new host's key; a *changed* host key stops the setup).
53
+ 3. **Server software** — creates the deploy directory (default `/opt/<project>` for root, `~/<project>` otherwise) and checks docker, docker compose, Node ≥ 18.17 and deployer, including installs made with nvm. It offers to install deployer when Node is there.
54
+ 4. **Registry access** — prints a link that creates the right token, e.g.
55
+ `https://github.com/settings/tokens/new?scopes=read:packages&description=<project>-vps-ghcr-pull`,
56
+ and asks you to paste it (hidden). The token is checked with GitHub (classic, `read:packages`, warns about broader scopes) and against each image on ghcr.io, then `docker login` runs **on the server** into the project's own docker config (`remote.dockerConfig`, `.docker` in the deploy directory). The token travels over ssh's stdin, never on a command line, and the server's other docker logins are left alone.
57
+ 5. **Save and verify** — writes `deployer.json`, then pulls the newest image on the server, printing the command so you can run the same check yourself:
58
+ `ssh root@203.0.113.10 'docker --config /opt/shop/.docker pull ghcr.io/acme/shop/web:latest'`.
59
+ Offers `deployer sync`, and points at a `.env.example` if the server has no `.env` yet.
60
+ 6. **This machine** — checks that builds can push (`GHCR_TOKEN`, your `gh` login with `write:packages`, or a `docker login`).
61
+
62
+ `deployer setup --check` runs every check without asking anything and exits 1 when the server is not ready — handy after a server rebuild or a token expiry. **Set up server** in the interactive UI starts the wizard.
63
+
40
64
  Your compose file selects each image's tag through a variable — that is what deployer moves:
41
65
 
42
66
  ```yaml
@@ -60,6 +84,7 @@ Run `deployer` with no command. Arrows / `j` `k` move, Enter or a **click** sele
60
84
  | **Status** | the tag each image runs, container states, the last deploy. |
61
85
  | **History** | past deploys on that server; Enter re-deploys an exact set of tags. |
62
86
  | **Sync to server** | copies `deployer.json` and your compose file(s) to the server. |
87
+ | **Set up server** | leaves the UI and runs `deployer setup`. |
63
88
 
64
89
  On the server the UI acts directly. On your build machine, if `deployer.json` has a `remote` section, the deploy screens drive the server over ssh (`deployer` must be installed there too).
65
90
 
@@ -74,6 +99,7 @@ deployer rollback --yes
74
99
  deployer status --json
75
100
  deployer history --json
76
101
  deployer sync
102
+ deployer setup --check
77
103
  deployer init --force
78
104
  global: -c/--config <file> (or $DEPLOYER_CONFIG), --help, --version
79
105
  ```
@@ -87,7 +113,7 @@ Exit codes: 0 success, 1 failure, 130 cancelled. Data goes to stdout (`--json`,
87
113
  3. Exports **the committed tree** with `git archive` — uncommitted edits and local `node_modules` never reach an image.
88
114
  4. Computes the tag from `version.format` (default `{version}-{sha}`, version read from `version.file` *at that commit*).
89
115
  5. Optionally runs your `checks` against that exported tree (`--checks`).
90
- 6. `docker buildx build --platform … --push` per image, with OCI labels (`source` links the GHCR package to the repo so it inherits its visibility, plus `revision`, `version`, `created`), tagged `:<tag>` and `:latest`.
116
+ 6. `docker buildx build --platform … --push` per image, with OCI labels (`revision`, `version`, `created`), tagged `:<tag>` and `:latest`. The `source` label **and** index annotation link the GHCR package to the repository, so it is listed under the repo's *Packages* and inherits its visibility and access. (buildx pushes an image index whenever it attaches provenance or builds several platforms, and GHCR reads the link from the index; a builder that pushes a single manifest gets a retry with the source on the manifest only.)
91
117
 
92
118
  Building on an Apple Silicon Mac for an x86 server: keep `"platforms": ["linux/amd64"]` and enable *Use Rosetta for x86_64/amd64 emulation* in Docker Desktop — it is many times faster than QEMU.
93
119
 
@@ -147,7 +173,8 @@ Building on an Apple Silicon Mac for an x86 server: keep `"platforms": ["linux/a
147
173
  "port": 22,
148
174
  "identityFile": "~/.ssh/deploy_key", // also sets IdentitiesOnly=yes
149
175
  "dir": "~/shop",
150
- "command": "deployer", // how to run deployer there
176
+ "command": "deployer", // how to run deployer there (setup writes the nvm form when needed)
177
+ "dockerConfig": ".docker", // DOCKER_CONFIG for this project, inside "dir": its own registry login
151
178
  "files": [{ "from": "deploy/docker-compose.prod.yml", "to": "docker-compose.yml" }]
152
179
  }
153
180
  }
package/dist/deployer.js CHANGED
@@ -292,7 +292,7 @@ var init_version = __esm({
292
292
  // src/util/exec.ts
293
293
  import { spawn } from "child_process";
294
294
  function run(cmd, args, opts = {}) {
295
- return new Promise((resolve2, reject) => {
295
+ return new Promise((resolve3, reject) => {
296
296
  let child;
297
297
  try {
298
298
  child = spawn(cmd, args, {
@@ -316,10 +316,10 @@ function run(cmd, args, opts = {}) {
316
316
  if (opts.input !== void 0) child.stdin?.end(opts.input);
317
317
  child.on("error", (err) => {
318
318
  if (err.name === "AbortError") reject(new CancelledError());
319
- else if (err.code === "ENOENT") resolve2({ code: 127, stdout, stderr: `${cmd}: command not found` });
319
+ else if (err.code === "ENOENT") resolve3({ code: 127, stdout, stderr: `${cmd}: command not found` });
320
320
  else reject(err);
321
321
  });
322
- child.on("close", (code) => resolve2({ code: code ?? 1, stdout, stderr }));
322
+ child.on("close", (code) => resolve3({ code: code ?? 1, stdout, stderr }));
323
323
  });
324
324
  }
325
325
  async function runOk(cmd, args, opts = {}) {
@@ -331,8 +331,18 @@ ${detail}` : ""}`);
331
331
  }
332
332
  return res.stdout.trim();
333
333
  }
334
+ function interactive(cmd, args) {
335
+ return new Promise((resolve3, reject) => {
336
+ const child = spawn(cmd, args, { stdio: "inherit" });
337
+ child.on("error", (e) => {
338
+ if (e.code === "ENOENT") resolve3(127);
339
+ else reject(e);
340
+ });
341
+ child.on("close", (code) => resolve3(code ?? 1));
342
+ });
343
+ }
334
344
  function stream(cmd, args, opts) {
335
- return new Promise((resolve2, reject) => {
345
+ return new Promise((resolve3, reject) => {
336
346
  if (opts.signal?.aborted) {
337
347
  reject(new CancelledError());
338
348
  return;
@@ -379,7 +389,7 @@ function stream(cmd, args, opts) {
379
389
  out2.flush();
380
390
  err.flush();
381
391
  if (opts.signal?.aborted) reject(new CancelledError());
382
- else resolve2(code ?? 1);
392
+ else resolve3(code ?? 1);
383
393
  });
384
394
  });
385
395
  }
@@ -569,6 +579,10 @@ function parseConfig(input, file) {
569
579
  if (raw.remote.files !== void 0 && (!Array.isArray(raw.remote.files) || raw.remote.files.some((f) => !isObj(f) || typeof f.from !== "string"))) {
570
580
  fail("remote.files", 'must be an array of { "from": "...", "to": "..." }');
571
581
  }
582
+ str(raw.remote.dockerConfig, "remote.dockerConfig");
583
+ if (raw.remote.port !== void 0 && !(Number.isInteger(raw.remote.port) && raw.remote.port > 0 && raw.remote.port < 65536)) {
584
+ fail("remote.port", "must be a port number (1-65535)");
585
+ }
572
586
  if (host && rdir) remote = { ...raw.remote, host, dir: rdir, command: raw.remote.command ?? "deployer" };
573
587
  }
574
588
  }
@@ -797,7 +811,7 @@ async function showFile(root, sha, path) {
797
811
  return res.code === 0 ? res.stdout : void 0;
798
812
  }
799
813
  function exportTree(root, sha, dest) {
800
- return new Promise((resolve2, reject) => {
814
+ return new Promise((resolve3, reject) => {
801
815
  const archive = spawn2("git", ["archive", "--format=tar", sha], { cwd: root, stdio: ["ignore", "pipe", "pipe"] });
802
816
  const tar = spawn2("tar", ["-x", "-C", dest], { stdio: ["pipe", "ignore", "pipe"] });
803
817
  let err = "";
@@ -815,7 +829,7 @@ function exportTree(root, sha, dest) {
815
829
  failed = true;
816
830
  reject(new DeployerError(`${what} failed while exporting ${sha.slice(0, 8)}: ${err.trim()}`));
817
831
  }
818
- if (--pending === 0 && !failed) resolve2();
832
+ if (--pending === 0 && !failed) resolve3();
819
833
  };
820
834
  archive.on("error", reject);
821
835
  tar.on("error", reject);
@@ -931,9 +945,12 @@ async function planBuild(project2, opts = {}) {
931
945
  for (const img of images) tags[img.key] = tagsFor(img, tag, sha, pushLatest);
932
946
  return { sha, ref, tag, images, pushLatest, tags };
933
947
  }
934
- function buildxArgs(image, plan, src, repo, created) {
948
+ function buildxArgs(image, plan, src, repo, created, annotate = "index,manifest") {
935
949
  const args = ["buildx", "build", "--platform", image.platforms.join(","), "--file", join4(src, image.dockerfile)];
936
- if (repo) args.push("--label", `org.opencontainers.image.source=https://github.com/${repo}`);
950
+ if (repo) {
951
+ const source = `org.opencontainers.image.source=https://github.com/${repo}`;
952
+ args.push("--label", source, "--annotation", `${annotate}:${source}`);
953
+ }
937
954
  args.push(
938
955
  "--label",
939
956
  `org.opencontainers.image.revision=${plan.sha}`,
@@ -953,7 +970,7 @@ async function build(project2, reporter, opts = {}) {
953
970
  const root = sourceRoot(project2);
954
971
  const { config } = project2;
955
972
  const plan = await planBuild(project2, opts);
956
- const check = () => {
973
+ const check2 = () => {
957
974
  if (opts.signal?.aborted) throw new CancelledError();
958
975
  };
959
976
  if (!opts.dryRun) {
@@ -969,14 +986,14 @@ async function build(project2, reporter, opts = {}) {
969
986
  if (pushed === false) reporter.warn(`Commit ${plan.sha.slice(0, 8)} is not pushed to the remote yet \u2014 push it so the release can be traced`);
970
987
  reporter.step(`Building ${plan.ref} (${plan.sha.slice(0, 8)}) as tag '${plan.tag}'`);
971
988
  reporter.info(`Images: ${plan.images.map((i) => i.key).join(" ")} \xB7 move :latest: ${plan.pushLatest ? "yes" : "no"}`);
972
- check();
989
+ check2();
973
990
  const src = mkdtempSync(join4(process.env.TMPDIR ?? tmpdir(), "deployer-build-"));
974
991
  const published = [];
975
992
  try {
976
993
  await exportTree(root, plan.sha, src);
977
994
  if (opts.runChecks && config.checks.length) {
978
995
  for (const ch of config.checks) {
979
- check();
996
+ check2();
980
997
  const cwd = join4(src, ch.cwd ?? ".");
981
998
  reporter.step(`Check: ${ch.name}`);
982
999
  if (opts.dryRun) {
@@ -989,16 +1006,31 @@ async function build(project2, reporter, opts = {}) {
989
1006
  }
990
1007
  }
991
1008
  const created = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
1009
+ let annotate = "index,manifest";
992
1010
  for (const image of plan.images) {
993
- check();
1011
+ check2();
994
1012
  const t0 = Date.now();
995
- const args = buildxArgs(image, plan, src, project2.repo, created);
996
1013
  reporter.step(`Building ${image.key} (${image.platforms.join(", ")})`);
997
1014
  if (opts.dryRun) {
1015
+ const args = buildxArgs(image, plan, src, project2.repo, created, annotate);
998
1016
  reporter.info(["docker", ...args].map((a) => shellQuote(a.replace(src, "<tree>"))).join(" "));
999
1017
  continue;
1000
1018
  }
1001
- const code = await stream("docker", args, { signal: opts.signal, onLine: (l) => reporter.output(l) });
1019
+ let code = 1;
1020
+ for (; ; ) {
1021
+ let indexRejected = false;
1022
+ const args = buildxArgs(image, plan, src, project2.repo, created, annotate);
1023
+ code = await stream("docker", args, {
1024
+ signal: opts.signal,
1025
+ onLine: (l) => {
1026
+ if (l.includes(INDEX_ANNOTATION_UNSUPPORTED)) indexRejected = true;
1027
+ reporter.output(l);
1028
+ }
1029
+ });
1030
+ if (code === 0 || !indexRejected || annotate === "manifest") break;
1031
+ annotate = "manifest";
1032
+ reporter.info("This builder pushes single-manifest images: retrying with the source on the manifest only");
1033
+ }
1002
1034
  if (code !== 0) throw new DeployerError(`Building ${image.key} failed (exit ${code})`);
1003
1035
  published.push(...plan.tags[image.key]);
1004
1036
  reporter.success(`${image.key} pushed in ${formatSeconds((Date.now() - t0) / 1e3)}`);
@@ -1023,6 +1055,7 @@ function rolloutCommand(plan) {
1023
1055
  if (keys.length === 0) return void 0;
1024
1056
  return `deployer deploy ${plan.tag} --images ${keys.join(",")} --yes`;
1025
1057
  }
1058
+ var INDEX_ANNOTATION_UNSUPPORTED;
1026
1059
  var init_build = __esm({
1027
1060
  "src/core/build.ts"() {
1028
1061
  "use strict";
@@ -1032,6 +1065,7 @@ var init_build = __esm({
1032
1065
  init_docker();
1033
1066
  init_git();
1034
1067
  init_project();
1068
+ INDEX_ANNOTATION_UNSUPPORTED = "index annotations not supported";
1035
1069
  }
1036
1070
  });
1037
1071
 
@@ -1602,6 +1636,21 @@ async function bearerFor(repository, creds) {
1602
1636
  const body = await res.json();
1603
1637
  return body.token ?? body.access_token;
1604
1638
  }
1639
+ async function pullAccess(repository, creds) {
1640
+ let bearer;
1641
+ try {
1642
+ bearer = await bearerFor(repository, creds);
1643
+ } catch {
1644
+ return "denied";
1645
+ }
1646
+ const headers = { "User-Agent": UA };
1647
+ if (bearer) headers.Authorization = `Bearer ${bearer}`;
1648
+ else headers.Authorization = `Basic ${Buffer.from(`${creds.username}:${creds.secret}`).toString("base64")}`;
1649
+ const res = await fetch(`${registryBase(registryOf(repository))}/v2/${repoPath(repository)}/tags/list`, { headers, signal: AbortSignal.timeout(15e3) });
1650
+ if (res.ok) return "ok";
1651
+ if (res.status === 404) return "missing";
1652
+ return "denied";
1653
+ }
1605
1654
  async function listFromRegistry(repository) {
1606
1655
  const registry = registryOf(repository);
1607
1656
  let creds = await dockerCredentials(registry);
@@ -1774,8 +1823,11 @@ function sshArgs(remote, command) {
1774
1823
  if (remote.port) args.push("-p", String(remote.port));
1775
1824
  return [...args, target(remote), command];
1776
1825
  }
1826
+ function dockerConfigPrefix(remote) {
1827
+ return remote.dockerConfig ? `export DOCKER_CONFIG=${remotePathExpr(remote.dockerConfig)} && ` : "";
1828
+ }
1777
1829
  function remoteCommand(remote, deployerArgs) {
1778
- return `cd ${remoteDirExpr(remote.dir)} && ${remote.command} ${deployerArgs.map(shellQuote).join(" ")}`;
1830
+ return `cd ${remoteDirExpr(remote.dir)} && ${dockerConfigPrefix(remote)}${remote.command} ${deployerArgs.map(shellQuote).join(" ")}`;
1779
1831
  }
1780
1832
  function sshCommandLine(remote, deployerArgs) {
1781
1833
  return ["ssh", ...sshArgs(remote, remoteCommand(remote, deployerArgs))].map(shellQuote).join(" ");
@@ -1828,8 +1880,13 @@ async function syncToRemote(project2, reporter, signal) {
1828
1880
  }
1829
1881
  }
1830
1882
  function remoteDirExpr(dir) {
1883
+ if (dir === "~") return '"$HOME"';
1831
1884
  return dir.startsWith("~/") ? `"$HOME"/${shellQuote(dir.slice(2))}` : shellQuote(dir);
1832
1885
  }
1886
+ function remotePathExpr(path) {
1887
+ if (path === "~" || path.startsWith("~/") || path.startsWith("/")) return remoteDirExpr(path);
1888
+ return `"$PWD"/${shellQuote(path.replace(/^\.\//, ""))}`;
1889
+ }
1833
1890
  async function remoteJson(config, deployerArgs) {
1834
1891
  const remote = needRemote(config);
1835
1892
  const res = await run("ssh", sshArgs(remote, remoteCommand(remote, deployerArgs)));
@@ -2169,6 +2226,764 @@ var init_commands = __esm({
2169
2226
  }
2170
2227
  });
2171
2228
 
2229
+ // src/core/setup.ts
2230
+ import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "fs";
2231
+ import { homedir as homedir3 } from "os";
2232
+ import { join as join8, posix as posix2 } from "path";
2233
+ function tokenDescription(name) {
2234
+ const slug = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "deployer";
2235
+ return `${slug}-vps-ghcr-pull`;
2236
+ }
2237
+ function tokenUrl(description, scopes = ["read:packages"]) {
2238
+ const safe = scopes.map((s) => /^[a-z:_]+$/.test(s) ? s : encodeURIComponent(s));
2239
+ return `https://github.com/settings/tokens/new?scopes=${safe.join(",")}&description=${encodeURIComponent(description)}`;
2240
+ }
2241
+ async function inspectGitHubToken(token) {
2242
+ let res;
2243
+ try {
2244
+ res = await fetch("https://api.github.com/user", {
2245
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "deployer-cli" },
2246
+ signal: AbortSignal.timeout(15e3)
2247
+ });
2248
+ } catch (err) {
2249
+ throw new DeployerError(`Could not reach api.github.com: ${err instanceof Error ? err.message : String(err)}`);
2250
+ }
2251
+ if (res.status === 401) throw new DeployerError("GitHub does not accept this token (expired, revoked or mistyped)");
2252
+ if (!res.ok) throw new DeployerError(`GitHub answered ${res.status} when checking the token`);
2253
+ const body = await res.json();
2254
+ const header = res.headers.get("x-oauth-scopes");
2255
+ return {
2256
+ login: body.login ?? "",
2257
+ scopes: header ? header.split(",").map((s) => s.trim()).filter(Boolean) : [],
2258
+ classic: header !== null
2259
+ };
2260
+ }
2261
+ function tokenScopeReport(info) {
2262
+ if (!info.classic) {
2263
+ return { ok: false, problem: "This is a fine-grained token: ghcr.io only accepts classic tokens. Create a classic one with the link.", extra: [] };
2264
+ }
2265
+ const canRead = info.scopes.includes("read:packages") || info.scopes.includes("write:packages");
2266
+ const extra = info.scopes.filter((s) => s !== "read:packages");
2267
+ return canRead ? { ok: true, extra } : { ok: false, problem: "The token is missing the read:packages scope.", extra };
2268
+ }
2269
+ function sshKeyCandidates(dir = join8(homedir3(), ".ssh")) {
2270
+ let names;
2271
+ try {
2272
+ names = readdirSync2(dir);
2273
+ } catch {
2274
+ return [];
2275
+ }
2276
+ const preferred = ["id_ed25519", "id_ecdsa", "id_rsa"];
2277
+ const keys = names.filter((n) => n.endsWith(".pub") && names.includes(n.slice(0, -4))).map((n) => n.slice(0, -4));
2278
+ keys.sort((a, b) => {
2279
+ const ia = preferred.indexOf(a);
2280
+ const ib = preferred.indexOf(b);
2281
+ return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib) || a.localeCompare(b);
2282
+ });
2283
+ return keys.map((k) => `~/.ssh/${k}`);
2284
+ }
2285
+ function expandTilde(p) {
2286
+ return p === "~" ? homedir3() : p.startsWith("~/") ? join8(homedir3(), p.slice(2)) : p;
2287
+ }
2288
+ function classifySshFailure(stderr) {
2289
+ const detail = stderr.trim().split("\n").filter(Boolean).pop() ?? "ssh failed";
2290
+ if (/REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(stderr)) return { ok: false, reason: "hostkey-changed", detail };
2291
+ if (/host key verification failed/i.test(stderr)) return { ok: false, reason: "hostkey-new", detail };
2292
+ if (/permission denied|too many authentication failures|no supported authentication/i.test(stderr)) return { ok: false, reason: "auth", detail };
2293
+ if (/could not resolve|connection refused|timed out|no route to host|network is unreachable/i.test(stderr)) return { ok: false, reason: "unreachable", detail };
2294
+ return { ok: false, reason: "other", detail };
2295
+ }
2296
+ async function testSsh(remote, opts = {}) {
2297
+ const withKey = opts.acceptNewHostKey ? { ...remote, sshArgs: [...remote.sshArgs ?? [], "-o", "StrictHostKeyChecking=accept-new"] } : remote;
2298
+ const res = await run("ssh", sshArgs(withKey, "true"));
2299
+ if (res.code === 0) return { ok: true };
2300
+ if (res.code === 127) return { ok: false, reason: "other", detail: "ssh is not installed on this machine" };
2301
+ return classifySshFailure(res.stderr);
2302
+ }
2303
+ async function createKey(path, comment) {
2304
+ const file = expandTilde(path);
2305
+ if (existsSync6(file)) return;
2306
+ const res = await run("ssh-keygen", ["-t", "ed25519", "-N", "", "-C", comment, "-f", file]);
2307
+ if (res.code !== 0) throw new DeployerError(`ssh-keygen failed: ${(res.stderr || res.stdout).trim().split("\n").pop()}`);
2308
+ }
2309
+ async function copyKey(remote, keyPath) {
2310
+ const args = ["-i", `${expandTilde(keyPath)}.pub`];
2311
+ if (remote.port) args.push("-p", String(remote.port));
2312
+ args.push("-o", "StrictHostKeyChecking=accept-new", target(remote));
2313
+ return await interactive("ssh-copy-id", args) === 0;
2314
+ }
2315
+ function withNvm(cmd) {
2316
+ return `bash -c ${shellQuote(`. "$HOME/.nvm/nvm.sh" >/dev/null 2>&1; ${cmd}`)}`;
2317
+ }
2318
+ function serverPath(dir, p) {
2319
+ if (p === "~" || p.startsWith("~/") || p.startsWith("/")) return remoteDirExpr(p);
2320
+ return remoteDirExpr(posix2.join(dir, p));
2321
+ }
2322
+ function probeScript(remote, envFile, registry) {
2323
+ const dir = remoteDirExpr(remote.dir);
2324
+ const cfg = serverPath(remote.dir, remote.dockerConfig ?? "~/.docker");
2325
+ return [
2326
+ 'echo "user=$(id -un)"',
2327
+ '[ -r /etc/os-release ] && . /etc/os-release && echo "os=$PRETTY_NAME"',
2328
+ `echo "docker_client=$(docker version --format '{{.Client.Version}}' 2>/dev/null)"`,
2329
+ `echo "docker_server=$(docker version --format '{{.Server.Version}}' 2>/dev/null)"`,
2330
+ 'echo "compose=$(docker compose version --short 2>/dev/null)"',
2331
+ `NVM=; [ -s "$HOME/.nvm/nvm.sh" ] && NVM=1 && echo nvm=1`,
2332
+ 'if command -v node >/dev/null 2>&1; then echo "node=$(node --version)"; echo node_via=path;',
2333
+ `elif [ -n "$NVM" ]; then V=$(${withNvm("node --version")} 2>/dev/null); [ -n "$V" ] && echo "node=$V" && echo node_via=nvm; fi`,
2334
+ 'if command -v deployer >/dev/null 2>&1; then echo "deployer=$(deployer --version)"; echo deployer_via=path;',
2335
+ `elif [ -n "$NVM" ]; then V=$(${withNvm("deployer --version")} 2>/dev/null); [ -n "$V" ] && echo "deployer=$V" && echo deployer_via=nvm; fi`,
2336
+ `[ -d ${dir} ] && echo dir=1`,
2337
+ `[ -f ${dir}/${shellQuote(envFile)} ] && echo env=1`,
2338
+ `[ -f ${cfg}/config.json ] && grep -q ${shellQuote(`"${registry}"`)} ${cfg}/config.json && echo login=1`,
2339
+ "true"
2340
+ ].join("\n");
2341
+ }
2342
+ function parseProbe(stdout) {
2343
+ const kv = /* @__PURE__ */ new Map();
2344
+ for (const line of stdout.split("\n")) {
2345
+ const i = line.indexOf("=");
2346
+ if (i > 0) kv.set(line.slice(0, i).trim(), line.slice(i + 1).trim());
2347
+ }
2348
+ const val = (k) => kv.get(k) || void 0;
2349
+ const via = (k) => kv.get(k) === "nvm" ? "nvm" : kv.get(k) === "path" ? "path" : void 0;
2350
+ return {
2351
+ user: kv.get("user") ?? "",
2352
+ os: val("os"),
2353
+ dockerClient: val("docker_client"),
2354
+ dockerServer: val("docker_server"),
2355
+ compose: val("compose"),
2356
+ nvm: kv.get("nvm") === "1",
2357
+ node: val("node"),
2358
+ nodeVia: via("node_via"),
2359
+ deployer: val("deployer"),
2360
+ deployerVia: via("deployer_via"),
2361
+ dirExists: kv.get("dir") === "1",
2362
+ envFile: kv.get("env") === "1",
2363
+ registryLogin: kv.get("login") === "1"
2364
+ };
2365
+ }
2366
+ async function probeServer(remote, envFile, registry) {
2367
+ const res = await run("ssh", sshArgs(remote, `sh -c ${shellQuote(probeScript(remote, envFile, registry))}`));
2368
+ if (res.code !== 0) throw new DeployerError(`Could not inspect ${remote.host}: ${(res.stderr || res.stdout).trim().split("\n").pop()}`);
2369
+ return parseProbe(res.stdout);
2370
+ }
2371
+ function deployerCommandFor(probe) {
2372
+ const via = probe.deployerVia ?? probe.nodeVia;
2373
+ return via === "nvm" ? ". ~/.nvm/nvm.sh >/dev/null 2>&1 && deployer" : "deployer";
2374
+ }
2375
+ function nodeMeetsFloor(version) {
2376
+ const m = /^v?(\d+)\.(\d+)/.exec(version ?? "");
2377
+ if (!m) return false;
2378
+ const [major, minor] = [Number(m[1]), Number(m[2])];
2379
+ return major > 18 || major === 18 && minor >= 17;
2380
+ }
2381
+ async function installDeployerOnServer(remote, probe, onLine) {
2382
+ const npm = `npm install -g ${PACKAGE}`;
2383
+ const cmd = probe.nodeVia === "nvm" ? withNvm(npm) : npm;
2384
+ return await stream("ssh", sshArgs(remote, cmd), { onLine }) === 0;
2385
+ }
2386
+ async function makeServerDir(remote) {
2387
+ const res = await run("ssh", sshArgs(remote, `mkdir -p ${remoteDirExpr(remote.dir)}`));
2388
+ if (res.code !== 0) throw new DeployerError(`Could not create ${remote.dir} on ${remote.host}: ${res.stderr.trim().split("\n").pop()}`);
2389
+ }
2390
+ async function serverRegistryLogin(remote, registry, username, token) {
2391
+ const cfg = serverPath(remote.dir, remote.dockerConfig ?? "~/.docker");
2392
+ const script = `mkdir -p ${cfg} && chmod 700 ${cfg} && docker --config ${cfg} login ${shellQuote(registry)} -u ${shellQuote(username)} --password-stdin`;
2393
+ const res = await run("ssh", sshArgs(remote, `sh -c ${shellQuote(script)}`), { input: `${token}
2394
+ ` });
2395
+ if (res.code !== 0) throw new DeployerError(`docker login on ${remote.host} failed: ${(res.stderr || res.stdout).trim().split("\n").pop()}`);
2396
+ }
2397
+ function pullCheckArgs(remote, image) {
2398
+ const docker = remote.dockerConfig ? `docker --config ${serverPath(remote.dir, remote.dockerConfig)}` : "docker";
2399
+ const ssh = [];
2400
+ if (remote.identityFile) ssh.push("-i", remote.identityFile);
2401
+ ssh.push(...remote.sshArgs ?? []);
2402
+ if (remote.port) ssh.push("-p", String(remote.port));
2403
+ return [...ssh, target(remote), `${docker} pull ${image}`];
2404
+ }
2405
+ function pullCheckLine(remote, image) {
2406
+ return ["ssh", ...pullCheckArgs(remote, image)].map(shellQuote).join(" ");
2407
+ }
2408
+ function classifyPullOutput(code, output) {
2409
+ if (code === 0) return "ok";
2410
+ if (/denied|unauthorized|authentication required/i.test(output)) return "denied";
2411
+ if (/manifest unknown|not found|name unknown/i.test(output)) return "missing";
2412
+ return "failed";
2413
+ }
2414
+ async function serverPull(remote, image, onLine) {
2415
+ let output = "";
2416
+ const args = sshArgs(remote, `cd ${remoteDirExpr(remote.dir)} 2>/dev/null; ${dockerConfigPrefix(remote)}docker pull ${shellQuote(image)}`);
2417
+ const code = await stream("ssh", args, { onLine: (l) => {
2418
+ output += `${l}
2419
+ `;
2420
+ onLine(l);
2421
+ } });
2422
+ return classifyPullOutput(code, output);
2423
+ }
2424
+ function readRawConfig(path) {
2425
+ return JSON.parse(readFileSync5(path, "utf8"));
2426
+ }
2427
+ function applySetup(raw, answers) {
2428
+ const remote = { ...raw.remote, ...answers.remote };
2429
+ if (remote.port === 22) delete remote.port;
2430
+ if (!remote.identityFile) delete remote.identityFile;
2431
+ if (remote.command === "deployer") delete remote.command;
2432
+ const order = ["host", "user", "port", "identityFile", "sshArgs", "dir", "command", "dockerConfig", "files"];
2433
+ const sorted = Object.fromEntries(
2434
+ [
2435
+ ...order.filter((k) => remote[k] !== void 0).map((k) => [k, remote[k]]),
2436
+ ...Object.entries(remote).filter(([k, v]) => !order.includes(k) && v !== void 0)
2437
+ ]
2438
+ );
2439
+ return { ...raw, ...answers.repo ? { repo: answers.repo } : {}, remote: sorted };
2440
+ }
2441
+ function writeRawConfig(path, raw) {
2442
+ writeFileSync5(path, `${JSON.stringify(raw, null, 2)}
2443
+ `);
2444
+ }
2445
+ function defaultRemoteDir(user, name) {
2446
+ return user === "root" ? `/opt/${name}` : `~/${name}`;
2447
+ }
2448
+ var PLACEHOLDER_HOST, DEFAULT_DOCKER_CONFIG, PACKAGE;
2449
+ var init_setup = __esm({
2450
+ "src/core/setup.ts"() {
2451
+ "use strict";
2452
+ init_errors();
2453
+ init_exec();
2454
+ init_remote();
2455
+ PLACEHOLDER_HOST = "your.server.example";
2456
+ DEFAULT_DOCKER_CONFIG = ".docker";
2457
+ PACKAGE = "@trojeancedric/deployer";
2458
+ }
2459
+ });
2460
+
2461
+ // src/cli/prompt.ts
2462
+ import { createInterface as createInterface2 } from "readline";
2463
+ var CYAN, GRAY2, useColor2, paint2, Prompter;
2464
+ var init_prompt = __esm({
2465
+ "src/cli/prompt.ts"() {
2466
+ "use strict";
2467
+ init_ansi();
2468
+ init_errors();
2469
+ CYAN = [103, 232, 249];
2470
+ GRAY2 = [148, 163, 184];
2471
+ useColor2 = () => process.stderr.isTTY && !("NO_COLOR" in process.env);
2472
+ paint2 = (color, text) => useColor2() ? fg(color, text) : text;
2473
+ Prompter = class {
2474
+ rl;
2475
+ closed = false;
2476
+ muted = false;
2477
+ constructor() {
2478
+ this.rl = createInterface2({ input: process.stdin, output: process.stderr, terminal: true });
2479
+ const rl = this.rl;
2480
+ const write = rl._writeToOutput.bind(rl);
2481
+ rl._writeToOutput = (s) => {
2482
+ if (!this.muted) write(s);
2483
+ else if (s.includes("\n") || s.includes("\r")) write("\n");
2484
+ };
2485
+ this.rl.on("close", () => {
2486
+ this.closed = true;
2487
+ });
2488
+ this.rl.on("SIGINT", () => {
2489
+ this.closed = true;
2490
+ this.rl.close();
2491
+ process.stderr.write("\n");
2492
+ this.reject?.(new CancelledError("Setup cancelled"));
2493
+ });
2494
+ }
2495
+ reject;
2496
+ question(text) {
2497
+ if (this.closed) return Promise.reject(new CancelledError("Setup cancelled"));
2498
+ return new Promise((resolve3, reject) => {
2499
+ this.reject = reject;
2500
+ const onClose = () => reject(new CancelledError("Setup cancelled"));
2501
+ this.rl.once("close", onClose);
2502
+ this.rl.question(text, (answer) => {
2503
+ this.rl.off("close", onClose);
2504
+ resolve3(answer);
2505
+ });
2506
+ });
2507
+ }
2508
+ label(q, def) {
2509
+ return `${paint2(CYAN, "?")} ${useColor2() ? bold(q) : q}${def ? paint2(GRAY2, ` (${def})`) : ""} `;
2510
+ }
2511
+ /** Free text; Enter keeps the default. `validate` returns an error message or undefined. */
2512
+ async ask(q, opts = {}) {
2513
+ for (; ; ) {
2514
+ const answer = (await this.question(this.label(q, opts.default))).trim() || opts.default || "";
2515
+ const problem = opts.validate?.(answer) ?? (answer ? void 0 : "An answer is needed");
2516
+ if (!problem) return answer;
2517
+ process.stderr.write(` ${paint2([248, 113, 113], problem)}
2518
+ `);
2519
+ }
2520
+ }
2521
+ async confirm(q, def = true) {
2522
+ for (; ; ) {
2523
+ const answer = (await this.question(this.label(q, def ? "Y/n" : "y/N"))).trim().toLowerCase();
2524
+ if (!answer) return def;
2525
+ if (/^y(es)?$/.test(answer)) return true;
2526
+ if (/^no?$/.test(answer)) return false;
2527
+ }
2528
+ }
2529
+ async choose(q, choices, def = 0) {
2530
+ process.stderr.write(`${this.label(q)}
2531
+ `);
2532
+ choices.forEach((c2, i) => {
2533
+ process.stderr.write(` ${paint2(CYAN, `${i + 1})`)} ${c2.label}${c2.hint ? paint2(GRAY2, ` ${c2.hint}`) : ""}
2534
+ `);
2535
+ });
2536
+ const n = Number(await this.ask("Choice", {
2537
+ default: String(def + 1),
2538
+ validate: (v) => /^\d+$/.test(v) && Number(v) >= 1 && Number(v) <= choices.length ? void 0 : `Pick 1-${choices.length}`
2539
+ }));
2540
+ return choices[n - 1].value;
2541
+ }
2542
+ /** Typed (or pasted) without being shown. */
2543
+ async secret(q) {
2544
+ for (; ; ) {
2545
+ process.stderr.write(this.label(q));
2546
+ this.muted = true;
2547
+ let answer;
2548
+ try {
2549
+ answer = (await this.question("")).trim();
2550
+ } finally {
2551
+ this.muted = false;
2552
+ }
2553
+ if (answer) return answer;
2554
+ process.stderr.write(` ${paint2([248, 113, 113], "Nothing was entered")}
2555
+ `);
2556
+ }
2557
+ }
2558
+ /** Hand the terminal to a child process that prompts by itself (ssh-copy-id), then take it back. */
2559
+ async suspend(fn) {
2560
+ this.rl.pause();
2561
+ const wasRaw = process.stdin.isTTY && process.stdin.isRaw;
2562
+ if (wasRaw) process.stdin.setRawMode(false);
2563
+ try {
2564
+ return await fn();
2565
+ } finally {
2566
+ if (wasRaw) process.stdin.setRawMode(true);
2567
+ this.rl.resume();
2568
+ }
2569
+ }
2570
+ close() {
2571
+ if (!this.closed) this.rl.close();
2572
+ }
2573
+ };
2574
+ }
2575
+ });
2576
+
2577
+ // src/cli/setup.ts
2578
+ var setup_exports = {};
2579
+ __export(setup_exports, {
2580
+ cmdSetup: () => cmdSetup
2581
+ });
2582
+ import { existsSync as existsSync7 } from "fs";
2583
+ import { join as join9, posix as posix3, resolve as resolve2 } from "path";
2584
+ function section(n, total, title) {
2585
+ const text = `\u2500\u2500 ${n}/${total} ${title} `;
2586
+ process.stderr.write(`
2587
+ ${useColor3() ? bold(text.padEnd(60, "\u2500")) : text}
2588
+ `);
2589
+ }
2590
+ function normalizeRepo(input) {
2591
+ const v = input.trim();
2592
+ if (/^[\w.-]+\/[\w.-]+$/.test(v)) return v.replace(/\.git$/, "");
2593
+ return parseRepoSlug(v);
2594
+ }
2595
+ function findConfigFile(flag) {
2596
+ try {
2597
+ return loadConfig(flag).file;
2598
+ } catch (err) {
2599
+ if (flag || !(err instanceof DeployerError) || !err.message.startsWith(`No ${CONFIG_FILE}`)) throw err;
2600
+ return void 0;
2601
+ }
2602
+ }
2603
+ function pulledImages(config, repo) {
2604
+ const prefix = config.imagePrefix ?? (repo ? `ghcr.io/${repo.toLowerCase()}` : "");
2605
+ resolveImages(config, prefix);
2606
+ return deployableImages(config).map((i) => i.repository);
2607
+ }
2608
+ function remoteFrom(config) {
2609
+ if (!config.remote) throw new DeployerError(`No "remote" section in ${config.file} \u2014 run \`deployer setup\` first`);
2610
+ const { host, user, port, identityFile, sshArgs: sshArgs2, dir, dockerConfig } = config.remote;
2611
+ return { host, user, port, identityFile, sshArgs: sshArgs2, dir, dockerConfig };
2612
+ }
2613
+ function displayPath(remote, p) {
2614
+ return p.startsWith("/") || p.startsWith("~") ? p : posix3.join(remote.dir, p);
2615
+ }
2616
+ function reportServer(probe, remote, envFile) {
2617
+ const problems = [];
2618
+ if (probe.os) mark.ok(`${probe.os} (as ${probe.user})`);
2619
+ if (probe.dockerServer) mark.ok(`docker ${probe.dockerServer}`);
2620
+ else if (probe.dockerClient) {
2621
+ mark.bad(`docker is installed but ${probe.user} cannot reach the daemon`);
2622
+ mark.hint(`start it (systemctl start docker) or: sudo usermod -aG docker ${probe.user}, then log in again`);
2623
+ problems.push("docker daemon not reachable");
2624
+ } else {
2625
+ mark.bad("docker is not installed");
2626
+ mark.hint("curl -fsSL https://get.docker.com | sh");
2627
+ problems.push("docker missing");
2628
+ }
2629
+ if (probe.compose) mark.ok(`docker compose ${probe.compose}`);
2630
+ else if (probe.dockerClient) {
2631
+ mark.bad("docker compose (v2 plugin) is missing");
2632
+ mark.hint("apt install docker-compose-plugin");
2633
+ problems.push("docker compose missing");
2634
+ }
2635
+ if (probe.node && nodeMeetsFloor(probe.node)) mark.ok(`node ${probe.node}${probe.nodeVia === "nvm" ? " (nvm)" : ""}`);
2636
+ else {
2637
+ mark.bad(probe.node ? `node ${probe.node} is too old (deployer needs \u2265 18.17)` : "node is not installed");
2638
+ mark.hint("Ubuntu: curl -fsSL https://deb.nodesource.com/setup_22.x | sudo bash - && sudo apt install -y nodejs");
2639
+ problems.push("node missing");
2640
+ }
2641
+ if (probe.deployer) mark.ok(`deployer ${probe.deployer}${probe.deployerVia === "nvm" ? " (nvm)" : ""}`);
2642
+ else {
2643
+ mark.bad("deployer is not installed");
2644
+ problems.push("deployer missing");
2645
+ }
2646
+ if (probe.dirExists) mark.ok(`deploy directory ${remote.dir}`);
2647
+ else {
2648
+ mark.bad(`${remote.dir} does not exist`);
2649
+ problems.push("deploy directory missing");
2650
+ }
2651
+ if (probe.envFile) mark.ok(`${posix3.join(remote.dir, envFile)} exists`);
2652
+ else mark.warn(`${posix3.join(remote.dir, envFile)} does not exist yet \u2014 create it with your secrets before deploying`);
2653
+ return problems;
2654
+ }
2655
+ async function reportPull(remote, image) {
2656
+ printHint(` Pull test (run it yourself any time):
2657
+ ${pullCheckLine(remote, image)}`);
2658
+ const result = await serverPull(remote, image, (l) => consoleReporter.output(l));
2659
+ if (result === "ok") mark.ok(`the server pulled ${image}`);
2660
+ else if (result === "missing") mark.warn(`the login works but ${image} is not published yet \u2014 run \`deployer build\``);
2661
+ else if (result === "denied") {
2662
+ mark.bad(`the registry refused ${image} to the server's login`);
2663
+ mark.hint("run `deployer setup` again and paste a new token");
2664
+ } else mark.bad(`pulling ${image} failed (see the output above)`);
2665
+ return result;
2666
+ }
2667
+ async function reportPushSide(registry) {
2668
+ if (registry !== "ghcr.io") {
2669
+ if (await isLoggedIn(registry)) {
2670
+ mark.ok(`this machine is logged in to ${registry}`);
2671
+ return true;
2672
+ }
2673
+ mark.warn(`this machine is not logged in to ${registry} \u2014 docker login ${registry}`);
2674
+ return false;
2675
+ }
2676
+ if (envToken()) {
2677
+ mark.ok("builds push with the token in GHCR_TOKEN / DEPLOYER_TOKEN / GITHUB_TOKEN");
2678
+ return true;
2679
+ }
2680
+ const status = await run("gh", ["auth", "status"]);
2681
+ if (status.code === 0 && (status.stdout + status.stderr).includes("write:packages")) {
2682
+ mark.ok("builds push with your gh login (write:packages)");
2683
+ return true;
2684
+ }
2685
+ if (await isLoggedIn(registry)) {
2686
+ mark.ok(`builds push with this machine's docker login to ${registry}`);
2687
+ return true;
2688
+ }
2689
+ mark.warn("this machine cannot push images yet");
2690
+ mark.hint(status.code === 127 ? "export GHCR_TOKEN=<token with write:packages>" : "gh auth refresh -h github.com -s write:packages");
2691
+ return false;
2692
+ }
2693
+ async function check(configFlag) {
2694
+ const config = loadConfig(configFlag);
2695
+ const remote = remoteFrom(config);
2696
+ const repo = config.repo ?? await gitRoot(config.root).then((root) => root ? originRepo(root) : void 0);
2697
+ const images = pulledImages(config, repo);
2698
+ const registry = images[0] ? registryOf(images[0]) : "ghcr.io";
2699
+ consoleReporter.step(`Checking ${PLACEHOLDER_HOST === remote.host ? "(no server set)" : `${remote.user ? `${remote.user}@` : ""}${remote.host}`}`);
2700
+ const ssh = await testSsh(remote);
2701
+ if (!ssh.ok) {
2702
+ mark.bad(`ssh: ${ssh.detail}`);
2703
+ throw new DeployerError("The server cannot be reached without a password prompt \u2014 run `deployer setup`");
2704
+ }
2705
+ mark.ok("ssh works without a password prompt");
2706
+ const probe = await probeServer(remote, config.deploy.envFile, registry);
2707
+ const problems = reportServer(probe, remote, config.deploy.envFile);
2708
+ const cfg = displayPath(remote, remote.dockerConfig ?? "~/.docker");
2709
+ if (probe.registryLogin) mark.ok(`${cfg} holds a ${registry} login`);
2710
+ else {
2711
+ mark.bad(`no ${registry} login in ${cfg}`);
2712
+ problems.push("registry login missing");
2713
+ }
2714
+ if (images[0] && probe.dockerServer) {
2715
+ const pulled = await reportPull(remote, `${images[0]}:latest`);
2716
+ if (pulled === "denied" || pulled === "failed") problems.push("pull failed");
2717
+ }
2718
+ await reportPushSide(registry);
2719
+ if (problems.length) throw new DeployerError(`Not ready to deploy: ${problems.join(", ")}`);
2720
+ consoleReporter.success("Everything is in place: deployer build --deploy");
2721
+ }
2722
+ async function wizard(p, configFlag) {
2723
+ process.stderr.write(`${useColor3() ? bold("deployer setup") : "deployer setup"} \u2014 connect this project to your server. Enter keeps the value in brackets.
2724
+ `);
2725
+ section(1, STEPS, "Project");
2726
+ let file = findConfigFile(configFlag);
2727
+ if (!file) {
2728
+ consoleReporter.info(`There is no ${CONFIG_FILE} here yet.`);
2729
+ if (!await p.confirm("Create one from the Dockerfiles in this repository?")) throw new DeployerError(`Setup needs a ${CONFIG_FILE}`);
2730
+ file = (await initConfig(process.cwd())).path;
2731
+ consoleReporter.success(`Wrote ${file} \u2014 check its image list afterwards`);
2732
+ }
2733
+ file = resolve2(file);
2734
+ let raw = readRawConfig(file);
2735
+ const config = loadConfig(file);
2736
+ const root = await gitRoot(config.root);
2737
+ const origin = root ? await originRepo(root) : void 0;
2738
+ const repo = normalizeRepo(await p.ask("GitHub repository (owner/name)", {
2739
+ default: raw.repo ?? origin,
2740
+ validate: (v) => normalizeRepo(v) ? void 0 : "Expected owner/name or a github.com URL"
2741
+ }));
2742
+ const name = config.name;
2743
+ const images = pulledImages(loadConfig(file), raw.imagePrefix ? void 0 : repo);
2744
+ if (images.length === 0) throw new DeployerError(`${file} has no image that compose runs on the server`);
2745
+ const registry = registryOf(images[0]);
2746
+ mark.ok(`images: ${images.join(", ")}`);
2747
+ section(2, STEPS, "Server");
2748
+ const old = raw.remote && raw.remote.host !== PLACEHOLDER_HOST ? raw.remote : void 0;
2749
+ const host = await p.ask("VPS host (IP address or domain)", {
2750
+ default: old?.host,
2751
+ validate: (v) => /^[\w.:-]+$/.test(v) ? void 0 : "Expected an IP address or a host name"
2752
+ });
2753
+ const port = Number(await p.ask("SSH port", {
2754
+ default: String(old?.port ?? 22),
2755
+ validate: (v) => /^\d+$/.test(v) && Number(v) > 0 && Number(v) < 65536 ? void 0 : "Expected a port number"
2756
+ }));
2757
+ const user = await p.ask("SSH user", { default: old?.user ?? "root", validate: (v) => /^[\w.-]+$/.test(v) ? void 0 : "Expected a user name" });
2758
+ const remote = { host, user, port: port === 22 ? void 0 : port, dir: "", sshArgs: old?.sshArgs };
2759
+ const words = [...name.toLowerCase().split(/[^a-z0-9]+/), host.toLowerCase()].filter((w) => w.length >= 3);
2760
+ const keys = sshKeyCandidates().filter((k) => {
2761
+ const base = k.slice(k.lastIndexOf("/") + 1).toLowerCase();
2762
+ return ["id_ed25519", "id_ecdsa", "id_rsa"].includes(base) || words.some((w) => base.includes(w));
2763
+ });
2764
+ const choices = [
2765
+ ...old?.identityFile ? [{ label: `Key file ${old.identityFile}`, value: { kind: "key", path: old.identityFile }, hint: "from deployer.json" }] : [],
2766
+ { label: "My usual ssh login", value: { kind: "agent" }, hint: "the keys plain `ssh user@host` uses" },
2767
+ ...keys.filter((k) => k !== old?.identityFile).map((k) => ({ label: `Key file ${k}`, value: { kind: "key", path: k } })),
2768
+ { label: "Another key file\u2026", value: { kind: "other" }, hint: "any private key, e.g. ~/.ssh/my_server" },
2769
+ { label: "Password", value: { kind: "password" }, hint: "deployer creates a key for this server and installs it with your password" }
2770
+ ];
2771
+ const auth = await p.choose("How do you log in to the server?", choices);
2772
+ let identityFile;
2773
+ if (auth.kind === "key") identityFile = auth.path;
2774
+ if (auth.kind === "other") {
2775
+ identityFile = await p.ask("Path to the private key", {
2776
+ validate: (v) => existsSync7(expandTilde(v)) ? void 0 : "No such file"
2777
+ });
2778
+ }
2779
+ if (auth.kind === "password") identityFile = await installKey(p, remote, name);
2780
+ remote.identityFile = identityFile;
2781
+ await connect(p, remote, name);
2782
+ section(3, STEPS, "Server software");
2783
+ remote.dir = await p.ask("Deploy directory on the server", {
2784
+ default: old?.dir && old.host === host ? old.dir : defaultRemoteDir(user, name)
2785
+ });
2786
+ remote.dockerConfig = old?.dockerConfig ?? DEFAULT_DOCKER_CONFIG;
2787
+ let probe = await probeServer(remote, config.deploy.envFile, registry);
2788
+ if (!probe.dirExists) {
2789
+ await makeServerDir(remote);
2790
+ probe = { ...probe, dirExists: true };
2791
+ consoleReporter.info(`Created ${remote.dir}`);
2792
+ }
2793
+ if (!probe.deployer && probe.node && nodeMeetsFloor(probe.node)) {
2794
+ if (await p.confirm(`deployer is not installed on ${host}. Install it now (npm install -g ${PACKAGE})?`)) {
2795
+ const ok = await installDeployerOnServer(remote, probe, (l) => consoleReporter.output(l));
2796
+ if (!ok) printError("npm install failed on the server (see above)");
2797
+ probe = await probeServer(remote, config.deploy.envFile, registry);
2798
+ }
2799
+ }
2800
+ const problems = reportServer(probe, remote, config.deploy.envFile);
2801
+ const command = probe.deployer ? deployerCommandFor(probe) : old?.command ?? "deployer";
2802
+ section(4, STEPS, "Registry access for the server");
2803
+ const cfgShown = displayPath(remote, remote.dockerConfig);
2804
+ consoleReporter.info(`The server pulls with its own login, kept in ${cfgShown} (other apps' docker logins are not touched).`);
2805
+ let login = !probe.registryLogin;
2806
+ if (probe.registryLogin) {
2807
+ mark.ok(`${cfgShown} already holds a ${registry} login`);
2808
+ login = await p.confirm("Replace it with a new token?", false);
2809
+ }
2810
+ if (login) {
2811
+ if (!probe.dockerClient) throw new DeployerError(`Install docker on ${host} first, then run deployer setup again`);
2812
+ if (registry === "ghcr.io") await ghcrLogin(p, remote, name, images);
2813
+ else {
2814
+ const username = await p.ask(`${registry} user name`);
2815
+ const secret = await p.secret(`${registry} password or token`);
2816
+ await serverRegistryLogin(remote, registry, username, secret);
2817
+ mark.ok(`the server is logged in to ${registry} as ${username}`);
2818
+ }
2819
+ }
2820
+ section(5, STEPS, "Save and verify");
2821
+ const answers = {
2822
+ host,
2823
+ user,
2824
+ port: remote.port,
2825
+ identityFile,
2826
+ dir: remote.dir,
2827
+ command,
2828
+ dockerConfig: remote.dockerConfig,
2829
+ ...raw.remote?.files ? { files: raw.remote.files } : {}
2830
+ };
2831
+ raw = applySetup(raw, { repo: raw.imagePrefix ? raw.repo : repo, remote: answers });
2832
+ writeRawConfig(file, raw);
2833
+ const saved = loadConfig(file);
2834
+ mark.ok(`saved ${file}`);
2835
+ let pulled;
2836
+ if (probe.dockerServer) {
2837
+ pulled = await reportPull(remote, `${images[0]}:latest`);
2838
+ if (pulled === "denied" || pulled === "failed") problems.push("the server cannot pull");
2839
+ }
2840
+ if (saved.remote && await p.confirm(`Copy ${CONFIG_FILE}${saved.remote.files?.length ? " and the compose files" : ""} to the server now (deployer sync)?`)) {
2841
+ await syncToRemote(await openProject(saved), consoleReporter);
2842
+ }
2843
+ if (!probe.envFile) {
2844
+ const template = ["deploy/.env.example", ".env.example", "deploy/.env.template"].find((f) => root && existsSync7(join9(root, f)));
2845
+ if (template) mark.hint(`start from ${template}: scp ${template} ${user}@${host}:${posix3.join(remote.dir, config.deploy.envFile)} then fill in the secrets there`);
2846
+ }
2847
+ section(6, STEPS, "This machine");
2848
+ await reportPushSide(registry);
2849
+ process.stderr.write("\n");
2850
+ if (problems.length) {
2851
+ printError(`Almost there \u2014 still to fix on ${host}: ${problems.join(", ")}. Then check again: deployer setup --check`);
2852
+ throw new DeployerError("Setup incomplete", 1);
2853
+ }
2854
+ consoleReporter.success(pulled === "ok" ? "Ready. Publish and deploy with: deployer build --deploy" : "Ready. Publish the first images and deploy them with: deployer build --deploy");
2855
+ }
2856
+ async function installKey(p, remote, name) {
2857
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "server";
2858
+ const key2 = `~/.ssh/deployer_${slug}`;
2859
+ await createKey(key2, `deployer@${name}`);
2860
+ mark.ok(`key ${key2} (no passphrase: deploys run unattended)`);
2861
+ consoleReporter.info(`Installing it on ${remote.host} \u2014 ssh-copy-id asks for ${remote.user}'s password once:`);
2862
+ const ok = await p.suspend(() => copyKey(remote, key2));
2863
+ if (!ok) throw new DeployerError("ssh-copy-id failed: check the password, or that password logins are allowed on the server");
2864
+ return key2;
2865
+ }
2866
+ async function connect(p, remote, name) {
2867
+ for (; ; ) {
2868
+ consoleReporter.step(`Connecting to ${remote.user}@${remote.host}${remote.port ? `:${remote.port}` : ""}`);
2869
+ let res = await testSsh(remote);
2870
+ if (!res.ok && res.reason === "hostkey-changed") {
2871
+ printError(`${remote.host}'s host key has CHANGED since you last connected. That can mean someone is intercepting the connection.
2872
+ If you rebuilt the server, remove the old key with: ssh-keygen -R ${remote.host}`);
2873
+ throw new DeployerError("Stopped: host key mismatch");
2874
+ }
2875
+ if (!res.ok && res.reason === "hostkey-new") {
2876
+ consoleReporter.info(`This machine has never connected to ${remote.host}.`);
2877
+ if (await p.confirm("Trust its host key and remember it?")) res = await testSsh(remote, { acceptNewHostKey: true });
2878
+ }
2879
+ if (res.ok) {
2880
+ mark.ok("ssh works without a password prompt (as every deploy needs)");
2881
+ return;
2882
+ }
2883
+ mark.bad(res.detail);
2884
+ const options = [{ label: "Try again", value: "retry" }];
2885
+ if (res.reason === "auth") options.push({ label: "Log in with the password once and install a key", value: "password" });
2886
+ options.push({ label: "Stop", value: "stop" });
2887
+ const next = await p.choose(res.reason === "unreachable" ? "The server is not reachable. Check the host, port and firewall." : "What now?", options);
2888
+ if (next === "stop") throw new DeployerError("Setup stopped: no ssh access");
2889
+ if (next === "password") remote.identityFile = await installKey(p, remote, name);
2890
+ }
2891
+ }
2892
+ async function ghcrLogin(p, remote, name, images) {
2893
+ const url = tokenUrl(tokenDescription(name));
2894
+ consoleReporter.info("Create a GitHub token the server can only use to download images:");
2895
+ process.stderr.write(`
2896
+ ${useColor3() ? bold(url) : url}
2897
+
2898
+ `);
2899
+ printHint(' Classic token \xB7 only "read:packages" ticked (the link does it) \xB7 pick an expiration.');
2900
+ printHint(' When it expires, deploys fail with "denied" until you run deployer setup again.\n');
2901
+ for (; ; ) {
2902
+ const token = await p.secret("Paste the token (hidden)");
2903
+ let info;
2904
+ try {
2905
+ info = await inspectGitHubToken(token);
2906
+ } catch (err) {
2907
+ mark.bad(err instanceof Error ? err.message : String(err));
2908
+ continue;
2909
+ }
2910
+ const scopes = tokenScopeReport(info);
2911
+ if (!scopes.ok) {
2912
+ mark.bad(scopes.problem);
2913
+ continue;
2914
+ }
2915
+ mark.ok(`token of ${info.login}, scopes: ${info.scopes.join(", ")}`);
2916
+ if (scopes.extra.length) {
2917
+ mark.warn(`it can also ${scopes.extra.join(", ")} \u2014 a server only needs read:packages`);
2918
+ if (!await p.confirm("Store it on the server anyway?", false)) continue;
2919
+ }
2920
+ let denied = false;
2921
+ for (const image of images) {
2922
+ const access = await pullAccess(image, { username: info.login, secret: token });
2923
+ if (access === "ok") mark.ok(`it can read ${image}`);
2924
+ else if (access === "missing") mark.warn(`${image} is not published yet (or not visible to ${info.login}) \u2014 fine before the first build`);
2925
+ else {
2926
+ mark.bad(`ghcr.io refuses ${image} to this token`);
2927
+ denied = true;
2928
+ }
2929
+ }
2930
+ if (denied) {
2931
+ mark.hint("the token must belong to an account that can read the repository's packages");
2932
+ continue;
2933
+ }
2934
+ await serverRegistryLogin(remote, "ghcr.io", info.login, token);
2935
+ mark.ok(`the server is logged in to ghcr.io as ${info.login} (the token went over ssh's stdin, not a command line)`);
2936
+ return;
2937
+ }
2938
+ }
2939
+ async function cmdSetup({ flags }) {
2940
+ const configFlag = typeof flags.config === "string" ? flags.config : void 0;
2941
+ if (flags.check) return check(configFlag);
2942
+ if (!process.stdin.isTTY || !process.stderr.isTTY) {
2943
+ throw new DeployerError("deployer setup asks questions: run it in a terminal (or check an existing setup with `deployer setup --check`)");
2944
+ }
2945
+ const p = new Prompter();
2946
+ try {
2947
+ await wizard(p, configFlag);
2948
+ } finally {
2949
+ p.close();
2950
+ }
2951
+ }
2952
+ var GREEN2, RED2, YELLOW2, useColor3, paint3, mark, STEPS;
2953
+ var init_setup2 = __esm({
2954
+ "src/cli/setup.ts"() {
2955
+ "use strict";
2956
+ init_config();
2957
+ init_docker();
2958
+ init_git();
2959
+ init_init();
2960
+ init_project();
2961
+ init_registry();
2962
+ init_remote();
2963
+ init_setup();
2964
+ init_ansi();
2965
+ init_errors();
2966
+ init_exec();
2967
+ init_reporter();
2968
+ init_prompt();
2969
+ GREEN2 = [52, 211, 153];
2970
+ RED2 = [248, 113, 113];
2971
+ YELLOW2 = [250, 204, 21];
2972
+ useColor3 = () => process.stderr.isTTY && !("NO_COLOR" in process.env);
2973
+ paint3 = (color, text) => useColor3() ? fg(color, text) : text;
2974
+ mark = {
2975
+ ok: (m) => process.stderr.write(` ${paint3(GREEN2, "\u2713")} ${m}
2976
+ `),
2977
+ bad: (m) => process.stderr.write(` ${paint3(RED2, "\u2717")} ${m}
2978
+ `),
2979
+ warn: (m) => process.stderr.write(` ${paint3(YELLOW2, "!")} ${m}
2980
+ `),
2981
+ hint: (m) => printHint(` ${m}`)
2982
+ };
2983
+ STEPS = 6;
2984
+ }
2985
+ });
2986
+
2172
2987
  // src/tui/input.ts
2173
2988
  function parseInput(data) {
2174
2989
  const events = [];
@@ -2444,8 +3259,8 @@ var init_app = __esm({
2444
3259
  }, 80);
2445
3260
  this.push(root);
2446
3261
  this.render();
2447
- return new Promise((resolve2) => {
2448
- this.resolveExit = resolve2;
3262
+ return new Promise((resolve3) => {
3263
+ this.resolveExit = resolve3;
2449
3264
  });
2450
3265
  }
2451
3266
  exit() {
@@ -4391,6 +5206,7 @@ var init_home = __esm({
4391
5206
  if (!p) {
4392
5207
  return [
4393
5208
  { label: "Create deployer.json", icon: "\u271A", shortcut: "i", description: "detect the Dockerfiles in this repository", action: () => void this.init() },
5209
+ this.setupItem("create deployer.json, then connect the server step by step"),
4394
5210
  { label: "Quit", icon: "\u23FB", shortcut: "q", action: () => this.app.exit() }
4395
5211
  ];
4396
5212
  }
@@ -4458,9 +5274,23 @@ var init_home = __esm({
4458
5274
  run: (rep, signal) => syncToRemote(p, rep, signal)
4459
5275
  })
4460
5276
  }] : [],
5277
+ ...p.canBuild ? [this.setupItem(p.config.remote ? `check or change ${p.config.remote.host}: ssh, deployer, registry token` : "connect a server: ssh, deployer, registry token")] : [],
4461
5278
  { label: "Quit", icon: "\u23FB", shortcut: "q", action: () => this.app.exit() }
4462
5279
  ];
4463
5280
  }
5281
+ /** The wizard asks line-by-line questions, so it runs after the UI closes. */
5282
+ setupItem(description) {
5283
+ return {
5284
+ label: "Set up server",
5285
+ icon: "\u2699",
5286
+ shortcut: "u",
5287
+ description,
5288
+ action: () => {
5289
+ this.ctx.then = "setup";
5290
+ this.app.exit();
5291
+ }
5292
+ };
5293
+ }
4464
5294
  async init() {
4465
5295
  try {
4466
5296
  const { path } = await initConfig(process.cwd());
@@ -4583,6 +5413,11 @@ async function launch(configPath) {
4583
5413
  } finally {
4584
5414
  app.exit();
4585
5415
  }
5416
+ if (ctx.then === "setup") {
5417
+ const { cmdSetup: cmdSetup2 } = await Promise.resolve().then(() => (init_setup2(), setup_exports));
5418
+ await cmdSetup2({ positionals: [], flags: configPath ? { config: configPath } : {} });
5419
+ return;
5420
+ }
4586
5421
  process.stderr.write(`${gradient("\u25B2 deployer", brandGradient)} bye.
4587
5422
  `);
4588
5423
  }
@@ -4674,6 +5509,20 @@ var COMMANDS = {
4674
5509
  flags: {},
4675
5510
  run: async () => (await Promise.resolve().then(() => (init_commands(), commands_exports))).cmdSync
4676
5511
  },
5512
+ setup: {
5513
+ summary: "Connect this project to its server, step by step (ssh, deployer, registry token)",
5514
+ usage: "deployer setup [--check]",
5515
+ details: [
5516
+ " Asks for the GitHub repository and the server (host, port, user, ssh key or",
5517
+ " password), checks ssh, docker and deployer there, stores a read-only registry",
5518
+ " token in the project's own docker config on the server, and proves it with a",
5519
+ " real pull. Run it again any time: current values are the defaults.",
5520
+ "",
5521
+ " --check run every check without asking anything (exit 1 if not ready)"
5522
+ ].join("\n"),
5523
+ flags: { check: {} },
5524
+ run: async () => (await Promise.resolve().then(() => (init_setup2(), setup_exports))).cmdSetup
5525
+ },
4677
5526
  init: {
4678
5527
  summary: "Create a deployer.json from the Dockerfiles in this repository",
4679
5528
  usage: "deployer init [--force]",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@trojeancedric/deployer",
3
- "version": "0.1.0",
4
- "description": "Build Docker images, push them to GHCR, then pull and deploy any version on a VPS \u2014 from one interactive CLI",
3
+ "version": "0.1.1",
4
+ "description": "Build Docker images, push them to GHCR, then pull and deploy any version on a VPS — from one interactive CLI",
5
5
  "keywords": [
6
6
  "docker",
7
7
  "deploy",