@sixb/deploy-ssh 0.2.5 → 0.2.7

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 (64) hide show
  1. package/README.md +51 -42
  2. package/dist/check/index.d.ts +24 -0
  3. package/dist/check/index.d.ts.map +1 -0
  4. package/dist/check/judge.d.ts +23 -0
  5. package/dist/check/judge.d.ts.map +1 -0
  6. package/dist/index.js +599 -1102
  7. package/dist/index.js.map +10 -15
  8. package/dist/layout.d.ts +91 -18
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -2
  11. package/dist/operations.d.ts.map +1 -1
  12. package/dist/plan.d.ts +25 -0
  13. package/dist/plan.d.ts.map +1 -0
  14. package/dist/render.d.ts +20 -10
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +15 -3
  17. package/dist/server/manifest.d.ts.map +1 -1
  18. package/dist/server/release-host.d.ts +4 -0
  19. package/dist/server/release-host.d.ts.map +1 -0
  20. package/dist/server/release.d.ts +46 -0
  21. package/dist/server/release.d.ts.map +1 -0
  22. package/dist/server/state.d.ts +2 -0
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +12 -4
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -18
  27. package/dist/ssh-target.d.ts.map +1 -1
  28. package/dist/transport.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/bootstrap.sh +93 -0
  31. package/src/check/index.ts +117 -0
  32. package/src/check/judge.ts +299 -0
  33. package/src/check/probe.sh +99 -0
  34. package/src/layout.ts +117 -34
  35. package/src/operations.ts +104 -61
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +128 -31
  38. package/src/server/cli.ts +26 -9
  39. package/src/server/manifest.ts +42 -4
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +3 -1
  43. package/src/server/supervisor.ts +127 -55
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +46 -227
  46. package/src/transport.ts +28 -12
  47. package/dist/access.d.ts +0 -11
  48. package/dist/access.d.ts.map +0 -1
  49. package/dist/check.d.ts +0 -31
  50. package/dist/check.d.ts.map +0 -1
  51. package/dist/ci.d.ts +0 -27
  52. package/dist/ci.d.ts.map +0 -1
  53. package/dist/keys.d.ts +0 -13
  54. package/dist/keys.d.ts.map +0 -1
  55. package/dist/scripts.d.ts +0 -38
  56. package/dist/scripts.d.ts.map +0 -1
  57. package/dist/setup.d.ts +0 -32
  58. package/dist/setup.d.ts.map +0 -1
  59. package/src/access.ts +0 -107
  60. package/src/check.ts +0 -231
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -323
  64. package/src/setup.ts +0 -203
package/dist/index.js CHANGED
@@ -2,334 +2,376 @@
2
2
  // src/ssh-target.ts
3
3
  import { isIPv6 } from "net";
4
4
 
5
- // src/access.ts
6
- import { createHash as createHash2 } from "crypto";
7
-
8
- // src/keys.ts
9
- import { createHash } from "crypto";
10
- var KEY_TYPES = new Set([
11
- "ssh-ed25519",
12
- "ssh-rsa",
13
- "ecdsa-sha2-nistp256",
14
- "ecdsa-sha2-nistp384",
15
- "ecdsa-sha2-nistp521",
16
- "sk-ssh-ed25519@openssh.com",
17
- "sk-ecdsa-sha2-nistp256@openssh.com"
18
- ]);
19
- function parseAuthorizedKey(line) {
20
- const trimmed = line.trim();
21
- if (!trimmed || trimmed.startsWith("#"))
22
- return null;
23
- const words = trimmed.split(/\s+/);
24
- const typeIndex = words.findIndex((word) => KEY_TYPES.has(word));
25
- if (typeIndex === -1)
26
- return null;
27
- const type = words[typeIndex] ?? "";
28
- const encoded = words[typeIndex + 1] ?? "";
29
- const blob = Buffer.from(encoded, "base64");
30
- const nameLength = blob.length >= 4 ? blob.readUInt32BE(0) : 0;
31
- if (blob.subarray(4, 4 + nameLength).toString() !== type)
32
- return null;
33
- const options = typeIndex > 0 ? words.slice(0, typeIndex).join(" ") : "";
34
- return {
35
- type,
36
- fingerprint: `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`,
37
- comment: words.slice(typeIndex + 2).join(" "),
38
- restricted: /(^|,)restrict(,|$)/.test(options),
39
- line: trimmed
40
- };
41
- }
42
- function parsePublicKey(text) {
43
- const key = parseAuthorizedKey(text);
44
- if (!key || key.line.includes(`
45
- `)) {
46
- throw new Error("[SshTarget] That is not an SSH public key. Pass the contents of a .pub file, such as " + "`ssh-ed25519 AAAA\u2026 you@laptop`.");
47
- }
48
- return key;
49
- }
5
+ // src/check/index.ts
6
+ import { resolve4, resolve6 } from "dns/promises";
7
+ import { isIP } from "net";
50
8
 
51
9
  // src/shell.ts
52
10
  function shellQuote(value) {
53
11
  return `'${value.replaceAll("'", `'"'"'`)}'`;
54
12
  }
55
- function writeFileCommand(path, content) {
56
- const encoded = Buffer.from(content, "utf8").toString("base64");
57
- return `printf '%s' ${shellQuote(encoded)} | base64 -d > ${shellQuote(path)}`;
58
- }
59
13
 
60
- // src/access.ts
61
- async function listKeys(shell) {
62
- return [...(await readKeysFile(shell)).keys];
14
+ // src/check/judge.ts
15
+ var HOST_REQUIREMENTS = "https://docs.sixb.ai/deployment/host-requirements";
16
+ var ENV_TOKEN_DOCS = "https://docs.sixb.ai/deployment/environment-variables#deploy";
17
+ var TOOL_PACKAGES = {
18
+ curl: "curl",
19
+ unzip: "unzip",
20
+ tar: "tar",
21
+ flock: "util-linux",
22
+ setsid: "util-linux",
23
+ sha256sum: "coreutils",
24
+ stat: "coreutils",
25
+ ss: "iproute2"
26
+ };
27
+ var INSTALL_CADDY = [
28
+ "curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
29
+ "curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
30
+ "apt-get update && apt-get install -y caddy"
31
+ ];
32
+ var MIN_CADDY = [2, 7];
33
+ var MIN_FREE_KB = 2 * 1024 * 1024;
34
+ var ARCHITECTURES = new Set(["x86_64", "amd64", "aarch64", "arm64"]);
35
+ function parseFacts(lines) {
36
+ const facts = new Map;
37
+ for (const line of lines) {
38
+ const [marker, key, ...value] = line.split("\t");
39
+ if (marker === "fact" && key)
40
+ facts.set(key, value.join("\t").trim());
41
+ }
42
+ return facts;
63
43
  }
64
- async function addKey(shell, text, options) {
65
- const parsed = parsePublicKey(text);
66
- const key = options ? parseAuthorizedKey(`${options} ${parsed.line}`) ?? parsed : parsed;
67
- const file = await readKeysFile(shell);
68
- if (file.keys.some((candidate) => candidate.fingerprint === key.fingerprint))
69
- return key;
70
- await rewrite(shell, [...file.lines, key.line], file.hash);
71
- return key;
44
+ function judge(facts, input) {
45
+ const user = pasteable(facts.get("account.name"));
46
+ const home = pasteable(facts.get("account.home"));
47
+ const root = home && pasteable(input.name) ? `${home}/${input.name}` : null;
48
+ return [
49
+ server(facts),
50
+ account(facts),
51
+ deployments(facts),
52
+ linger(facts, user),
53
+ caddy(facts, user),
54
+ settings(facts, input.settings, root),
55
+ ports(facts, input.ports),
56
+ ...input.chromium ? [chromium(facts)] : [],
57
+ disk(facts)
58
+ ];
72
59
  }
73
- async function removeKeys(shell, match) {
74
- const removed = await removeKeysWhere(shell, (key) => key.fingerprint === match || key.comment === match);
75
- if (removed.length === 0) {
76
- throw new Error(`[SshTarget] No authorized key has the fingerprint or comment '${match}'.`);
77
- }
78
- return removed;
60
+ function server(facts) {
61
+ const name = facts.get("os.name") || "an unknown system";
62
+ const family = `${facts.get("os.id") ?? ""} ${facts.get("os.like") ?? ""}`;
63
+ const arch = facts.get("os.arch") ?? "";
64
+ const missing = facts.get("os.missing") ?? "";
65
+ const problems = [
66
+ /\b(debian|ubuntu)\b/.test(family) ? "" : `${name} is not Ubuntu or Debian`,
67
+ facts.get("os.systemd") === "yes" ? "" : "systemd is missing",
68
+ ARCHITECTURES.has(arch) ? "" : `Bun has no build for ${arch || "this CPU"}`,
69
+ missing ? `missing ${missing.split(" ").join(", ")}` : ""
70
+ ].filter(Boolean);
71
+ const packages = [...new Set(missing.split(" ").flatMap((tool) => TOOL_PACKAGES[tool] ?? []))];
72
+ return problems.length === 0 ? ok("server", "Server", `${name}, ${arch}`) : fail("server", "Server", problems.join("; "), {
73
+ commands: packages.length > 0 ? [`apt-get install -y ${packages.join(" ")}`] : []
74
+ });
79
75
  }
80
- async function removeKeysWhere(shell, matches) {
81
- const file = await readKeysFile(shell);
82
- const removed = file.keys.filter(matches);
83
- if (removed.length === 0)
84
- return [];
85
- if (removed.length === file.keys.length) {
86
- throw new Error("[SshTarget] That would remove every key, and nobody could reach the deployment. " + "Add another key first.");
87
- }
88
- const gone = new Set(removed.map((key) => key.line));
89
- await rewrite(shell, file.lines.filter((line) => !gone.has(line.trim())), file.hash);
90
- return removed;
76
+ function account(facts) {
77
+ const name = facts.get("account.name") || "an unknown account";
78
+ return facts.get("account.uid") === "0" ? fail("account", "Account", `${name} is root: deploy as an account without root access`) : ok("account", "Account", name);
91
79
  }
92
- async function readKeysFile(shell) {
93
- const encoded = [];
94
- await shell.run('(base64 < "$HOME/.ssh/authorized_keys" 2> /dev/null || true) | tr -d "\\n"', {
95
- onLine: (line, stream) => {
96
- if (stream === "stdout")
97
- encoded.push(line);
80
+ function deployments(facts) {
81
+ const others = (facts.get("deployments.others") ?? "").split(" ").filter(Boolean);
82
+ return others.length === 0 ? ok("deployments", "Deployments", "none other on this server") : fail("deployments", "Deployments", `this server already runs ${others.join(", ")}: a server runs one deployment`);
83
+ }
84
+ function linger(facts, user) {
85
+ return facts.get("linger") === "yes" ? ok("linger", "Services at boot", "lingering is on") : fail("linger", "Services at boot", "lingering is off: the services would stop at logout", {
86
+ commands: user ? [`loginctl enable-linger ${user}`] : []
87
+ });
88
+ }
89
+ function caddy(facts, user) {
90
+ const version = facts.get("caddy.version") ?? "";
91
+ const routes = facts.get("caddy.routes") ?? "the routes folder";
92
+ const problems = [
93
+ !version ? "Caddy is not installed" : atLeast(version, MIN_CADDY) ? "" : `Caddy ${version} is older than ${MIN_CADDY.join(".")}`,
94
+ facts.get("caddy.caddyfile-imports") === "yes" ? "" : "/etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy",
95
+ facts.get("caddy.routes-imported") === "yes" ? "" : `nothing imports ${routes}`,
96
+ facts.get("caddy.routes-writable") === "yes" ? "" : `${routes} is missing or not writable`,
97
+ facts.get("caddy.reload") === "yes" ? "" : "sudo systemctl reload caddy is not allowed"
98
+ ].filter(Boolean);
99
+ if (problems.length === 0)
100
+ return ok("caddy", "Caddy", `${version}, routes in ${routes}`);
101
+ const folder = `/etc/caddy/sixb.d/${user}`;
102
+ const configure = !user ? [] : [
103
+ ...facts.get("caddy.caddyfile-imports") === "yes" ? [] : [
104
+ "grep -qxF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || echo 'import /etc/caddy/sixb.d/*.caddy' >> /etc/caddy/Caddyfile"
105
+ ],
106
+ ...facts.get("caddy.routes-imported") === "yes" ? [] : [
107
+ "install -d -m 0755 /etc/caddy/sixb.d",
108
+ `echo 'import ${folder}/*.caddy' > ${folder}.caddy`
109
+ ],
110
+ ...facts.get("caddy.routes-writable") === "yes" ? [] : [`install -d -m 0755 -o ${user} -g ${user} ${folder}`],
111
+ ...facts.get("caddy.reload") === "yes" ? [] : [
112
+ `echo '${user} ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > /etc/sudoers.d/${user}`,
113
+ `chmod 440 /etc/sudoers.d/${user}`
114
+ ]
115
+ ];
116
+ const install = !version ? INSTALL_CADDY : atLeast(version, MIN_CADDY) ? [] : ["apt-get update && apt-get install -y --only-upgrade caddy"];
117
+ return fail("caddy", "Caddy", problems.join("; "), {
118
+ commands: [
119
+ ...install,
120
+ ...configure,
121
+ ...configure.length > 0 ? ["systemctl reload caddy"] : []
122
+ ]
123
+ });
124
+ }
125
+ function settings(facts, source, root) {
126
+ const folder = root ?? "~/<name>";
127
+ if (source === "identity") {
128
+ return ok("settings", "Settings", "the source reads with the server's own identity");
129
+ }
130
+ if (source === "env-token") {
131
+ const token = fileFact(facts.get("file.env-token"));
132
+ if (!token || token.size === 0) {
133
+ return fail("settings", "Settings", "no env token: the deploy can't pull .env", {
134
+ remedy: `Put a read-only token for the project's prod values at ${folder}/env-token, mode 600. See ${ENV_TOKEN_DOCS}.`
135
+ });
98
136
  }
137
+ return privateMode(token.mode) ? ok("settings", "Settings", "env token in place") : fail("settings", "Settings", `the env token is readable by others (mode ${token.mode})`, {
138
+ commands: root ? [`chmod 600 ${root}/env-token`] : []
139
+ });
140
+ }
141
+ const shared = fileFact(facts.get("file.shared-env"));
142
+ const env = shared ?? fileFact(facts.get("file.legacy-env"));
143
+ if (!env) {
144
+ return fail("settings", "Settings", "no .env on the server", {
145
+ remedy: `Create ${folder}/shared/.env, mode 600, with the project's settings.`
146
+ });
147
+ }
148
+ return privateMode(env.mode) ? ok("settings", "Settings", ".env in place") : fail("settings", "Settings", `.env is readable by others (mode ${env.mode})`, {
149
+ commands: shared && root ? [`chmod 600 ${root}/shared/.env`] : []
99
150
  });
100
- const content = Buffer.from(encoded.join(""), "base64").toString("utf8");
101
- const lines = content.split(`
102
- `).filter((line, index, all) => line || index < all.length - 1);
151
+ }
152
+ function ports(facts, wanted) {
153
+ const taken = wanted.filter((port) => facts.get(`port.${port}`) === "other");
154
+ return taken.length === 0 ? ok("ports", "Ports", wanted.join(", ")) : fail("ports", "Ports", `${taken.join(", ")} ${taken.length === 1 ? "is" : "are"} held by another program: a server runs one deployment`);
155
+ }
156
+ function chromium(facts) {
157
+ const missing = facts.get("chromium.missing") ?? "";
158
+ const checked = facts.get("chromium.checked") ?? "system libraries";
159
+ return missing ? fail("chromium", "Chromium", `missing ${missing.split(" ").join(", ")} (${checked})`, {
160
+ remedy: "Install them as root, such as with `npx playwright install-deps chromium`."
161
+ }) : ok("chromium", "Chromium", "its libraries are installed");
162
+ }
163
+ function disk(facts) {
164
+ const freeKb = Number(facts.get("disk.free-kb") ?? 0);
165
+ return freeKb >= MIN_FREE_KB ? ok("disk", "Disk space", `${Math.floor(freeKb / 1048576)} GB free`) : {
166
+ id: "disk",
167
+ label: "Disk space",
168
+ status: "warning",
169
+ detail: `${Math.floor(freeKb / 1024)} MB free`,
170
+ remedy: "A release needs about 1 GB while it builds."
171
+ };
172
+ }
173
+ function ok(id, label, detail) {
174
+ return { id, label, status: "ok", detail };
175
+ }
176
+ function fail(id, label, detail, fix = {}) {
177
+ const commands = fix.commands ?? [];
103
178
  return {
104
- lines,
105
- keys: lines.flatMap((line) => parseAuthorizedKey(line) ?? []),
106
- hash: sha256(content)
179
+ id,
180
+ label,
181
+ status: "fail",
182
+ detail,
183
+ remedy: fix.remedy ?? `See ${HOST_REQUIREMENTS}.`,
184
+ ...commands.length > 0 ? { commands } : {}
107
185
  };
108
186
  }
109
- async function rewrite(shell, lines, readHash) {
110
- const content = `${lines.join(`
111
- `)}
112
- `;
113
- await shell.run([
114
- "set -euo pipefail",
115
- 'keys="$HOME/.ssh/authorized_keys"',
116
- 'mkdir -p -m 700 "$HOME/.ssh"',
117
- 'current="$( (cat "$keys" 2> /dev/null || true) | sha256sum | cut -d" " -f1)"',
118
- `if [ "$current" != ${shellQuote(readHash)} ]; then`,
119
- ' echo "authorized_keys changed while this ran; run the command again." >&2',
120
- " exit 1",
121
- "fi",
122
- `printf '%s' ${shellQuote(Buffer.from(content).toString("base64"))} | base64 -d > "$keys.new"`,
123
- 'chmod 600 "$keys.new"',
124
- 'mv "$keys.new" "$keys"'
125
- ].join(`
126
- `));
187
+ function pasteable(value) {
188
+ return value && /^[A-Za-z0-9._/-]+$/.test(value) ? value : null;
127
189
  }
128
- function sha256(content) {
129
- return createHash2("sha256").update(content).digest("hex");
190
+ function privateMode(mode) {
191
+ const bits = Number.parseInt(mode, 8);
192
+ return Number.isInteger(bits) && (bits & 63) === 0;
193
+ }
194
+ function fileFact(value) {
195
+ if (!value || value === "missing")
196
+ return null;
197
+ const [mode = "", size = "0"] = value.split(" ");
198
+ return { mode, size: Number(size) };
199
+ }
200
+ function atLeast(version, minimum) {
201
+ const parts = version.split(".").map((part) => Number.parseInt(part, 10) || 0);
202
+ for (const [index, wanted] of minimum.entries()) {
203
+ const part = parts[index] ?? 0;
204
+ if (part !== wanted)
205
+ return part > wanted;
206
+ }
207
+ return true;
130
208
  }
131
209
 
132
- // src/check.ts
133
- import { resolve4, resolve6 } from "dns/promises";
134
- import { isIP } from "net";
135
- import { posix as posix2 } from "path";
210
+ // src/check/probe.sh
211
+ var probe_default = `# Reports what a deploy needs to know about the server, as the deploy account, changing nothing.
212
+ # Prints one \`fact<TAB>key<TAB>value\` line per fact; check/judge.ts decides what each means.
213
+ # The caller sets SIXB_NAME (the deployment), SIXB_PROJECT (the project's path in its repository),
214
+ # SIXB_PORTS (the slots' loopback ports) and SIXB_CHROMIUM (1 when the project prints with
215
+ # Chromium) above this script.
136
216
 
137
- // src/layout.ts
138
- import { posix } from "path";
139
- var ENV_TOKEN_FILE = "env-token";
140
- function deploymentLayout(input) {
141
- const root = posix.join(input.home, input.name);
142
- const code = posix.join(root, "code");
143
- const deployDir = posix.join(root, "deploy");
144
- const runDir = posix.join(root, "run");
145
- const bunDir = posix.join(input.home, ".sixb", "bun", input.bunVersion);
146
- const unitName = `sixb-${input.name}.service`;
147
- const caddyDir = posix.join("/etc/caddy/sixb.d", input.user);
148
- return {
149
- root,
150
- code,
151
- envToken: posix.join(root, ENV_TOKEN_FILE),
152
- project: posix.join(code, input.projectPath),
153
- deployDir,
154
- incomingDir: posix.join(deployDir, "incoming"),
155
- lock: posix.join(deployDir, "lock"),
156
- fileList: posix.join(deployDir, "files.txt"),
157
- manifest: posix.join(deployDir, "processes.json"),
158
- releaseRecord: posix.join(deployDir, "release.json"),
159
- ctl: posix.join(deployDir, "ctl"),
160
- runDir,
161
- logDir: posix.join(runDir, "logs"),
162
- bunDir,
163
- bun: posix.join(bunDir, "bun"),
164
- unitName,
165
- unit: posix.join(input.home, ".config", "systemd", "user", unitName),
166
- caddyDir,
167
- caddySnippet: posix.join(caddyDir, `${input.name}.caddy`)
168
- };
169
- }
217
+ fact() { printf 'fact\\t%s\\t%s\\n' "$1" "$(printf '%s' "$2" | tr '\\t\\n' ' ')"; }
218
+ yes_no() { if "$@" > /dev/null 2>&1; then echo yes; else echo no; fi; }
219
+
220
+ # Server
221
+ # In a subshell: os-release sets NAME, ID and others over this script's own variables.
222
+ if [ -r /etc/os-release ]; then
223
+ (
224
+ # shellcheck disable=SC1091
225
+ . /etc/os-release
226
+ fact os.id "\${ID:-}"
227
+ fact os.like "\${ID_LIKE:-}"
228
+ fact os.name "\${PRETTY_NAME:-}"
229
+ )
230
+ fi
231
+ fact os.systemd "$(yes_no command -v systemctl)"
232
+ fact os.arch "$(uname -m)"
233
+ missing=""
234
+ for tool in curl unzip tar flock setsid sha256sum ss; do
235
+ command -v "$tool" > /dev/null || missing="$missing $tool"
236
+ done
237
+ # The deploy reads modes with GNU stat's \`-c\`.
238
+ stat -c %a "$HOME" > /dev/null 2>&1 || missing="$missing stat"
239
+ fact os.missing "\${missing# }"
240
+ fact account.name "$(id -un)"
241
+ fact account.home "$HOME"
242
+ fact account.uid "$(id -u)"
243
+ fact linger "$(yes_no test -e "/var/lib/systemd/linger/$USER")"
170
244
 
171
- // src/check.ts
172
- var CHECK_MARKER = "__SIXB_CHECK__";
173
- var TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"];
174
- var ENV_TOKEN_CHECK = "project.env-token";
175
- function renderCheckScript(input) {
176
- const project = posix2.join(input.name, "code", input.projectPath);
177
- const envToken = posix2.join(input.name, ENV_TOKEN_FILE);
245
+ # Caddy
246
+ fact caddy.version "$(caddy version 2> /dev/null | cut -d' ' -f1 | sed 's/^v//')"
247
+ fact caddy.reload "$(yes_no sudo -n -l /usr/bin/systemctl reload caddy)"
248
+ routes="/etc/caddy/sixb.d/$USER"
249
+ fact caddy.routes "$routes"
250
+ fact caddy.routes-writable "$(yes_no test -d "$routes" -a -w "$routes")"
251
+ fact caddy.routes-imported "$(yes_no grep -qsF "import $routes/*.caddy" "/etc/caddy/sixb.d/$USER.caddy")"
252
+ fact caddy.caddyfile-imports "$(yes_no grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile)"
253
+
254
+ # Deployments on this server, by their systemd units: a server runs one
255
+ others="$(
256
+ for unit in "$HOME"/.config/systemd/user/sixb-*.service; do
257
+ [ -e "$unit" ] || continue
258
+ deployment="\${unit##*/sixb-}"
259
+ deployment="\${deployment%.service}"
260
+ deployment="\${deployment%@}"
261
+ [ "$deployment" = "$SIXB_NAME" ] || echo "$deployment"
262
+ done | sort -u | tr '\\n' ' '
263
+ )"
264
+ fact deployments.others "\${others% }"
265
+
266
+ # Settings: the token a deploy pulls .env with, or the .env kept on the server
267
+ file_fact() {
268
+ if [ -f "$2" ]; then fact "$1" "$(stat -c '%a %s' "$2")"; else fact "$1" missing; fi
269
+ }
270
+ root="$HOME/$SIXB_NAME"
271
+ file_fact file.env-token "$root/env-token"
272
+ file_fact file.shared-env "$root/shared/.env"
273
+ # A deployment from before releases kept its .env in its code folder, which the first deploy moves.
274
+ if [ ! -L "$root/code" ]; then
275
+ file_fact file.legacy-env "$root/code/$SIXB_PROJECT/.env"
276
+ fi
277
+
278
+ # Ports: free, held by this account, or held by something else
279
+ uid="$(id -u)"
280
+ for port in $SIXB_PORTS; do
281
+ listening="$(ss -ltnHe "sport = :$port" 2> /dev/null)"
282
+ if [ -z "$listening" ]; then
283
+ fact "port.$port" free
284
+ elif printf '%s' "$listening" | grep -q "uid:$uid\\\\b"; then
285
+ fact "port.$port" own
286
+ else
287
+ fact "port.$port" other
288
+ fi
289
+ done
290
+
291
+ fact disk.free-kb "$(df -Pk "$HOME" | awk 'NR == 2 { print $4 + 0 }')"
292
+
293
+ # Chromium: the libraries the downloaded browser can't find, or, before the first download, the
294
+ # few that a server without Chromium's dependencies lacks
295
+ if [ "\${SIXB_CHROMIUM:-0}" = 1 ]; then
296
+ browser="$(find "$HOME/.cache/ms-playwright" -path '*/chrome-headless-shell-linux64/chrome-headless-shell' -type f 2> /dev/null | sort -V | tail -n 1)"
297
+ if [ -n "$browser" ]; then
298
+ fact chromium.checked "$browser"
299
+ fact chromium.missing "$(ldd "$browser" 2> /dev/null | awk '/not found/ { print $1 }' | tr '\\n' ' ')"
300
+ else
301
+ fact chromium.checked "system libraries"
302
+ ldconfig="$(command -v ldconfig || echo /sbin/ldconfig)"
303
+ missing=""
304
+ for lib in libnss3.so libatk-1.0.so.0 libatk-bridge-2.0.so.0 libgbm.so.1 libxkbcommon.so.0 libasound.so.2; do
305
+ "$ldconfig" -p 2> /dev/null | grep -qF "$lib" || missing="$missing $lib"
306
+ done
307
+ fact chromium.missing "\${missing# }"
308
+ fi
309
+ fi
310
+ `;
311
+
312
+ // src/check/index.ts
313
+ async function checkHost(shell, input) {
314
+ const lines = [];
315
+ await shell.run(renderProbe(input), {
316
+ onLine: (line, stream) => {
317
+ if (stream === "stdout")
318
+ lines.push(line);
319
+ }
320
+ });
321
+ return judge(parseFacts(lines), input);
322
+ }
323
+ function renderProbe(input) {
178
324
  return [
179
- `emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
180
- `project="$HOME"/${shellQuote(project)}`,
181
- `manifest="$HOME"/${shellQuote(input.name)}/deploy/processes.json`,
182
- 'routes_dir="/etc/caddy/sixb.d/$USER"',
183
- `snippet="$routes_dir"/${shellQuote(`${input.name}.caddy`)}`,
184
- "",
185
- "if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then",
186
- ' emit server.os ok "$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',
187
- "else",
188
- ' emit server.os manual "$(uname -s) without apt and systemd"',
189
- "fi",
190
- "",
191
- 'missing=""',
192
- `for tool in ${TOOLS.join(" ")}; do command -v "$tool" > /dev/null || missing="$missing $tool"; done`,
193
- 'if [ -n "$missing" ]; then emit server.tools fixable "missing:$missing"',
194
- 'else emit server.tools ok "Caddy $(caddy version 2>/dev/null | cut -d" " -f1), git, curl, unzip"; fi',
195
- "",
196
- 'if [ -e "/var/lib/systemd/linger/$USER" ]; then emit server.linger ok "on for $USER"',
197
- 'else emit server.linger fixable "off for $USER: services would stop when you log out"; fi',
198
- "",
199
- "if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
200
- ' emit server.reload ok "$USER may reload Caddy"',
201
- "else",
202
- ' emit server.reload fixable "$USER may not run sudo systemctl reload caddy"',
203
- "fi",
204
- "",
205
- 'problems=""',
206
- '[ -d "$routes_dir" ] && [ -w "$routes_dir" ] || problems="$problems; $routes_dir is missing or not writable"',
207
- 'grep -qsF "import $routes_dir/*.caddy" "/etc/caddy/sixb.d/$USER.caddy" || problems="$problems; /etc/caddy/sixb.d/$USER.caddy does not import it"',
208
- `grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems="$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy"`,
209
- 'if [ -z "$problems" ]; then emit server.routes ok "$routes_dir"',
210
- `else emit server.routes fixable "$(printf '%s' "$problems" | sed 's/^; //')"; fi`,
211
- "",
212
- "if ss -ltnH 2> /dev/null | grep -qE '(127\\.0\\.0\\.1|\\[::1\\]):2019 '; then",
213
- ` emit server.admin-api warning "Caddy's admin API listens on localhost:2019, where any process on the server can change every route"`,
214
- "else",
215
- ' emit server.admin-api ok "not on localhost:2019"',
216
- "fi",
217
- "",
218
- ...input.envFromSource ? [
219
- `token="$HOME"/${shellQuote(envToken)}`,
220
- `if [ ! -s "$token" ]; then emit ${ENV_TOKEN_CHECK} fixable "$token has no token"`,
221
- `elif [ "$(stat -c %a "$token")" != 600 ]; then emit ${ENV_TOKEN_CHECK} fixable "$token is readable by others (mode $(stat -c %a "$token"))"`,
222
- `else emit ${ENV_TOKEN_CHECK} ok "$token"; fi`
223
- ] : [
224
- 'if [ ! -f "$project/.env" ]; then emit project.env manual "$project/.env does not exist"',
225
- 'elif [ "$(stat -c %a "$project/.env")" != 600 ]; then emit project.env fixable "$project/.env is readable by others (mode $(stat -c %a "$project/.env"))"',
226
- 'else emit project.env ok "$project/.env"; fi'
227
- ],
228
- "",
229
- ...input.ports.flatMap(({ service, port }) => [
230
- `if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
231
- ` if grep -qs '"--port",' "$manifest" && grep -A1 -s '"--port",' "$manifest" | grep -q '"${port}"'; then`,
232
- ` emit project.port.${service} ok "${port}, used by this deployment"`,
233
- " else",
234
- ` emit project.port.${service} manual "${port} is in use by another program"`,
235
- " fi",
236
- `elif grep -ls '127.0.0.1:${port}\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv "^$snippet$"; then`,
237
- ` emit project.port.${service} manual "${port} is routed to another deployment"`,
238
- "else",
239
- ` emit project.port.${service} ok "${port}"`,
240
- "fi"
241
- ]),
242
- "",
243
- `free_kb="$(df -Pk "$HOME" | awk 'NR == 2 { print $4 + 0 }')"`,
244
- 'if [ "$free_kb" -lt 2097152 ]; then emit server.disk warning "$((free_kb / 1024)) MB free"',
245
- 'else emit server.disk ok "$((free_kb / 1048576)) GB free"; fi'
325
+ `SIXB_NAME=${shellQuote(input.name)}`,
326
+ `SIXB_PROJECT=${shellQuote(input.projectPath)}`,
327
+ `SIXB_PORTS=${shellQuote(input.ports.join(" "))}`,
328
+ `SIXB_CHROMIUM=${input.chromium ? 1 : 0}`,
329
+ probe_default
246
330
  ].join(`
247
331
  `);
248
332
  }
249
- function parseCheckOutput(lines, context) {
250
- return lines.flatMap((line) => {
251
- const [marker, id, status, detail] = line.split("\t");
252
- if (marker !== CHECK_MARKER || !id || !isStatus(status))
253
- return [];
254
- return [describe(id, status, detail ?? "", context)];
255
- });
256
- }
257
333
  async function checkDns(release, hostname) {
258
- const expected = isIP(hostname) ? [hostname] : await lookup(hostname);
334
+ const server = isIP(hostname) ? [hostname] : await lookup(hostname);
335
+ const comparable = server.length > 0 && server.every((address) => !isPrivateAddress(address));
259
336
  return Promise.all(release.services.flatMap((service) => {
260
- const http = service.http;
261
- if (!http)
337
+ const domain = service.http?.domain;
338
+ if (!domain)
262
339
  return [];
263
340
  return [
264
341
  (async () => {
265
- const found = await lookup(http.domain);
342
+ const found = await lookup(domain);
266
343
  const id = `dns.${service.name}`;
267
344
  const label = `${service.name} DNS`;
268
- if (expected.length > 0 && found.some((address) => expected.includes(address))) {
269
- return { id, label, status: "ok", detail: `${http.domain} \u2192 ${found.join(", ")}` };
345
+ const detail = `${domain} \u2192 ${found.join(", ")}`;
346
+ if (found.length === 0) {
347
+ return {
348
+ id,
349
+ label,
350
+ status: "warning",
351
+ detail: `${domain} does not resolve`,
352
+ remedy: `Point ${domain} at the server. Until then, Caddy cannot get it a certificate.`
353
+ };
354
+ }
355
+ if (!comparable || found.some((address) => server.includes(address))) {
356
+ return { id, label, status: "ok", detail };
270
357
  }
271
- const target = expected[0] ?? hostname;
358
+ const target = server[0] ?? hostname;
272
359
  return {
273
360
  id,
274
361
  label,
275
362
  status: "warning",
276
- detail: found.length > 0 ? `${http.domain} \u2192 ${found.join(", ")}` : `${http.domain} does not resolve`,
277
- remedy: `Point ${http.domain} at ${target} with an ${isIP(target) === 6 ? "AAAA" : "A"} record. Until then, Caddy cannot get it a certificate.`
363
+ detail,
364
+ remedy: `Point ${domain} at ${target} with an ${isIP(target) === 6 ? "AAAA" : "A"} record. Until then, Caddy cannot get it a certificate.`
278
365
  };
279
366
  })()
280
367
  ];
281
368
  }));
282
369
  }
283
- async function runChecks(shell, input) {
284
- const lines = [];
285
- await shell.run(renderCheckScript(input), {
286
- onLine: (line, stream) => {
287
- if (stream === "stdout")
288
- lines.push(line);
289
- }
290
- });
291
- return parseCheckOutput(lines, input);
292
- }
293
- var LABELS = {
294
- "server.os": "Server",
295
- "server.tools": "Server tools",
296
- "server.linger": "Services at boot",
297
- "server.reload": "Caddy reload",
298
- "server.routes": "Caddy routes",
299
- "server.admin-api": "Caddy admin API",
300
- "server.disk": "Disk space",
301
- "project.env": ".env",
302
- [ENV_TOKEN_CHECK]: "Source token"
303
- };
304
- function describe(id, status, detail, context) {
305
- const label = LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13)} port` : id);
306
- const check = { id, label, status, detail };
307
- if (status === "ok")
308
- return check;
309
- if (status === "fixable")
310
- return { ...check, remedy: "Run `sixb deploy setup`." };
311
- if (id === "server.os")
312
- return { ...check, remedy: "Deploy to an Ubuntu or Debian server." };
313
- if (id === "project.env") {
314
- const path = detail.replace(/ does not exist$/, "");
315
- return {
316
- ...check,
317
- remedy: `Create it with the project's settings: \`ssh ${context.location} 'install -m 600 /dev/null ${path}'\`, then edit it.`
318
- };
319
- }
320
- if (id.startsWith("project.port.")) {
321
- return { ...check, remedy: "Give this service another port in the target's `ports`." };
322
- }
323
- if (id === "server.admin-api") {
324
- return {
325
- ...check,
326
- remedy: "Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile."
327
- };
328
- }
329
- return check;
330
- }
331
- function isStatus(value) {
332
- return value === "ok" || value === "fixable" || value === "manual" || value === "warning";
370
+ function isPrivateAddress(address) {
371
+ if (isIP(address) === 6)
372
+ return /^f[cd]/i.test(address) || address === "::1";
373
+ const [a = 0, b = 0] = address.split(".").map(Number);
374
+ return a === 10 || a === 127 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127;
333
375
  }
334
376
  async function lookup(hostname) {
335
377
  const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))]);
@@ -349,486 +391,145 @@ async function settle(query) {
349
391
  }
350
392
  }
351
393
 
352
- // src/ci.ts
353
- import { mkdtemp, readFile, rm } from "fs/promises";
354
- import { tmpdir } from "os";
355
- import { join } from "path";
356
- async function generateCiKey(comment) {
357
- const dir = await mkdtemp(join(tmpdir(), "sixb-ci-key-"));
358
- try {
359
- const path = join(dir, "key");
360
- const child = Bun.spawn(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", path], {
361
- stdin: "ignore",
362
- stdout: "ignore",
363
- stderr: "pipe"
364
- });
365
- if (await child.exited !== 0) {
366
- const reason = (await new Response(child.stderr).text()).trim();
367
- throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`);
368
- }
369
- return {
370
- privateKey: await readFile(path, "utf8"),
371
- publicKey: (await readFile(`${path}.pub`, "utf8")).trim()
372
- };
373
- } finally {
374
- await rm(dir, { recursive: true, force: true });
375
- }
376
- }
377
- async function readHostKeys(shell) {
378
- const keys = [];
379
- await shell.run("cat /etc/ssh/ssh_host_*_key.pub", {
380
- onLine: (line, stream) => {
381
- const [type, key] = line.trim().split(/\s+/);
382
- if (stream === "stdout" && type && key)
383
- keys.push(`${type} ${key}`);
384
- }
385
- });
386
- if (keys.length === 0)
387
- throw new Error("[SshTarget] Could not read the server's SSH host keys.");
388
- return keys;
389
- }
390
- function knownHostsLines(hostKeys, hostname, port) {
391
- const name = port === 22 ? hostname : `[${hostname}]:${port}`;
392
- return hostKeys.map((key) => `${name} ${key}`);
393
- }
394
- function renderCiInstall(input) {
395
- return [
396
- "install -d -m 700 ~/.ssh",
397
- "install -m 600 /dev/null ~/.ssh/sixb_deploy",
398
- `printf '%s\\n' "$SIXB_DEPLOY_SSH_KEY" > ~/.ssh/sixb_deploy`,
399
- `printf '%s\\n' "$SIXB_DEPLOY_KNOWN_HOSTS" > ~/.ssh/sixb_known_hosts`,
400
- "cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'",
401
- `Host ${input.host}`,
402
- ` HostName ${input.hostname}`,
403
- ` Port ${input.port}`,
404
- " IdentityFile ~/.ssh/sixb_deploy",
405
- " IdentitiesOnly yes",
406
- " UserKnownHostsFile ~/.ssh/sixb_known_hosts",
407
- " StrictHostKeyChecking yes",
408
- "__SIXB_SSH_CONFIG__"
409
- ];
410
- }
394
+ // src/layout.ts
395
+ var SLOT_PORTS = {
396
+ blue: { app: 3001, api: 3002 },
397
+ green: { app: 3011, api: 3012 }
398
+ };
411
399
 
412
400
  // src/operations.ts
413
401
  import { randomUUID } from "crypto";
414
402
 
415
- // src/update-page.ts
416
- function renderUpdatePage() {
417
- return `<!doctype html>
418
- <html lang="en">
419
- <head>
420
- <meta charset="utf-8">
421
- <meta name="viewport" content="width=device-width, initial-scale=1">
422
- <meta http-equiv="refresh" content="10">
423
- <title>Updates in progress</title>
424
- <style>
425
- :root { color-scheme: light dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #fff; color: #111; --muted: #666; --line: #e8e8e8; --surface: #fafafa; --track: #d6d6d6; }
426
- * { box-sizing: border-box; }
427
- body { margin: 0; min-height: 100vh; min-height: 100svh; display: grid; place-items: center; padding: 48px 28px; -webkit-font-smoothing: antialiased; }
428
- main { width: 100%; max-width: 480px; }
429
- .status { display: inline-flex; align-items: center; gap: 9px; margin-bottom: 28px; padding: 8px 11px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; font-weight: 500; line-height: 1.4; letter-spacing: 0.1em; text-transform: uppercase; }
430
- .loader { width: 12px; height: 12px; flex: none; border: 1.5px solid var(--track); border-top-color: currentColor; border-radius: 50%; animation: spin 1s linear infinite; }
431
- h1 { margin: 0 0 16px; font-size: clamp(28px, 5vw, 36px); font-weight: 500; letter-spacing: -0.045em; line-height: 1.2; text-wrap: balance; }
432
- .description { margin: 0; max-width: 380px; color: var(--muted); font-size: 15px; line-height: 1.8; text-wrap: pretty; }
433
- .footer { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 8px 20px; margin-top: 36px; padding-top: 20px; border-top: 1px solid var(--line); color: var(--muted); }
434
- .footer p { margin: 0; font-size: 12px; line-height: 1.6; }
435
- .footer .interval { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; letter-spacing: 0.02em; }
436
- @keyframes spin { to { transform: rotate(360deg); } }
437
- @media (prefers-reduced-motion: reduce) { .loader { animation: none; } }
438
- @media (prefers-color-scheme: dark) {
439
- :root { background: #0a0a0a; color: #f5f5f5; --muted: #999; --line: #262626; --surface: #111; --track: #444; }
440
- }
441
- </style>
442
- </head>
443
- <body>
444
- <main>
445
- <div class="status"><span class="loader" aria-hidden="true"></span>Site update</div>
446
- <h1>Updates in progress</h1>
447
- <p class="description">We\u2019re making a few updates. The site should be back soon. Thanks for your patience.</p>
448
- <div class="footer">
449
- <p>This page will reconnect automatically.</p>
450
- <p class="interval">Retrying every 10s</p>
451
- </div>
452
- </main>
453
- </body>
454
- </html>`;
455
- }
403
+ // src/bootstrap.sh
404
+ var bootstrap_default = `# Starts a release on the server: takes the deploy lock, unpacks the upload into its release
405
+ # folder, installs Bun and the dependencies, then hands over to the release's own runner
406
+ # (server/release.ts), which still holds the lock. Runs detached from the SSH session, so a
407
+ # dropped connection never leaves half a deploy; the laptop follows its log.
408
+ #
409
+ # Usage: bootstrap.sh <name> <release-id> <project-path> <bun-version> <incoming> <plan>
456
410
 
457
- // src/render.ts
458
- var GENERATED = "Generated by sixb deploy. Changes are replaced on the next deploy.";
459
- function renderProcessManifest(release, layout) {
460
- const sixb = `${layout.project}/node_modules/.bin/sixb`;
461
- return {
462
- version: 1,
463
- name: release.name,
464
- cwd: layout.project,
465
- runDir: layout.runDir,
466
- logDir: layout.logDir,
467
- releasePath: layout.releaseRecord,
468
- env: release.env,
469
- services: release.services.map((service) => ({
470
- name: service.name,
471
- processName: `${release.name}-${service.name}`,
472
- command: layout.bun,
473
- args: service.command.program === "sixb" ? [sixb, ...service.command.args] : [...service.command.args],
474
- env: service.env,
475
- instances: service.instances,
476
- killTimeoutMs: service.process.killTimeoutMs,
477
- restartDelayMs: service.process.restartDelayMs,
478
- ...service.process.maxMemory ? { maxMemory: service.process.maxMemory } : {}
479
- }))
480
- };
481
- }
482
- function renderCtl(layout) {
483
- return [
484
- "#!/bin/sh",
485
- `# ${GENERATED}`,
486
- `exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} "$@" --manifest ${shellQuote(layout.manifest)}`,
487
- ""
488
- ].join(`
489
- `);
490
- }
491
- function renderUnit(release, layout) {
492
- const stopSeconds = Math.ceil(Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000) + 10;
493
- return [
494
- `# ${GENERATED}`,
495
- "[Unit]",
496
- `Description=Sixb deployment ${release.name}`,
497
- "",
498
- "[Service]",
499
- "Type=simple",
500
- `WorkingDirectory=${systemdValue(layout.project)}`,
501
- `Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,
502
- `ExecStart=${systemdValue(layout.ctl)} supervise`,
503
- "Restart=always",
504
- "RestartSec=2",
505
- "KillSignal=SIGTERM",
506
- `TimeoutStopSec=${stopSeconds}`,
507
- "",
508
- "[Install]",
509
- "WantedBy=default.target",
510
- ""
511
- ].join(`
512
- `);
513
- }
514
- function renderCaddySnippet(release) {
515
- const sites = release.services.flatMap((service) => {
516
- if (!service.http)
517
- return [];
518
- const pages = service.name === "app";
519
- return [
520
- [
521
- `${service.http.domain} {`,
522
- ...service.name === "api" ? compressJson() : [],
523
- ` reverse_proxy ${service.http.host}:${service.http.port}`,
524
- ...pages ? updatePageOnProxyErrors() : [],
525
- "}"
526
- ].join(`
527
- `)
528
- ];
529
- });
530
- return [`# ${GENERATED}`, "", sites.join(`
411
+ set -euo pipefail
412
+ name=$1 release_id=$2 project_path=$3 bun_version=$4 incoming=$5 plan=$6
531
413
 
532
- `), ""].join(`
533
- `);
534
- }
535
- function compressJson() {
536
- return [
537
- "\tencode {",
538
- "\t\tzstd",
539
- "\t\tgzip",
540
- "\t\tmatch {",
541
- "\t\t\tstatus 200",
542
- "\t\t\theader Content-Type application/json*",
543
- "\t\t}",
544
- "\t}"
545
- ];
546
- }
547
- function updatePageOnProxyErrors() {
548
- return [
549
- "\thandle_errors 502 503 504 {",
550
- "\t\t@page {",
551
- "\t\t\tmethod GET",
552
- "\t\t\theader Accept *text/html*",
553
- "\t\t}",
554
- "\t\thandle @page {",
555
- '\t\t\theader Content-Type "text/html; charset=utf-8"',
556
- '\t\t\theader Cache-Control "no-store"',
557
- '\t\t\theader Retry-After "10"',
558
- "\t\t\trespond 503 {",
559
- "\t\t\t\tbody <<HTML",
560
- ...renderUpdatePage().split(`
561
- `).map((line) => ` ${line}`),
562
- "\t\t\t\tHTML",
563
- "\t\t\t}",
564
- "\t\t}",
565
- "\t\thandle {",
566
- '\t\t\trespond "Service temporarily unavailable" {err.status_code}',
567
- "\t\t}",
568
- "\t}"
569
- ];
570
- }
571
- function systemdValue(value) {
572
- return value.replace(/%/g, "%%").replace(/\s/g, "\\x20");
573
- }
414
+ root="$HOME/$name"
415
+ release="$root/releases/$release_id"
416
+ project="$release/$project_path"
417
+ bun_dir="$HOME/.sixb/bun/$bun_version"
418
+ bun="$bun_dir/bun"
574
419
 
575
- // src/scripts.ts
576
- var STEP_MARKER = "__SIXB_STEP__";
577
- function renderPrepareScript(name, commit) {
578
- return [
579
- `root="$HOME"/${shellQuote(name)}`,
580
- 'mkdir -p "$root/deploy/incoming"',
581
- `incoming="$(mktemp -d "$root/deploy/incoming/${commit.slice(0, 12)}.XXXXXX")"`,
582
- 'chmod 755 "$incoming"',
583
- `printf '%s\\n%s\\n' "$HOME" "$incoming"`
584
- ].join(`
585
- `);
586
- }
587
- function renderReceiveScript(incoming, path) {
588
- const directory = path === "." ? incoming : `${incoming}/${path}`;
589
- return `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`;
590
- }
591
- function renderDeployScript(input) {
592
- const { release, layout } = input;
593
- const api = release.services.find((service) => service.http?.readinessPath);
594
- const steps = [
595
- { label: "Apply files", body: renderApplyFiles(layout, input.incoming) },
596
- { label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },
597
- { label: "Install dependencies", body: renderInstallDependencies() },
598
- ...release.steps.env ? [envStep(release.steps.env, layout)] : [],
599
- ...release.steps.build.map((command) => runStep(command)),
600
- { label: "Write services", body: renderWriteServices(release, layout) },
601
- { label: "Update routes", body: renderUpdateRoutes(release, layout) },
602
- { label: "Stop services", body: renderStopServices() },
603
- ...release.steps.beforeStart.map((command) => runStep(command)),
604
- { label: "Start services", body: renderStartServices() },
605
- {
606
- label: "Check services",
607
- body: renderCheckServices(api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null)
608
- },
609
- {
610
- label: "Record release",
611
- body: writeFileCommand(layout.releaseRecord, `${JSON.stringify(input.record)}
612
- `)
613
- }
614
- ];
615
- const script = [
616
- "set -euo pipefail",
617
- "main() {",
618
- renderEnvironment(release, layout),
619
- renderTakeLock(layout),
620
- ...steps.flatMap((step, index) => [
621
- `printf '\\n%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} start`,
622
- step.body,
623
- `printf '%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} done`
624
- ]),
625
- "}",
626
- "main </dev/null",
627
- ""
628
- ].join(`
629
- `);
630
- return { labels: steps.map((step) => step.label), script };
631
- }
632
- function renderEnvironment(release, layout) {
633
- const variables = {
634
- ROOT: layout.root,
635
- CODE: layout.code,
636
- PROJECT: layout.project,
637
- DEPLOY: layout.deployDir,
638
- BUN: layout.bun,
639
- BUN_DIR: layout.bunDir,
640
- BUN_VERSION: release.bunVersion,
641
- CTL: layout.ctl,
642
- UNIT: layout.unitName,
643
- UNIT_PATH: layout.unit,
644
- CADDY_DIR: layout.caddyDir,
645
- CADDY_SNIPPET: layout.caddySnippet
646
- };
647
- return [
648
- ...Object.entries(variables).map(([name, value]) => `${name}=${shellQuote(value)}`),
649
- ...Object.entries(release.env).map(([name, value]) => `export ${name}=${shellQuote(value)}`),
650
- 'export PATH="$BUN_DIR:$PATH"',
651
- 'printenv XDG_RUNTIME_DIR > /dev/null || export XDG_RUNTIME_DIR="/run/user/$(id -u)"'
652
- ].join(`
653
- `);
654
- }
655
- function renderTakeLock(layout) {
656
- return [
657
- `exec 9>${shellQuote(layout.lock)}`,
658
- "if ! flock -n 9; then",
659
- ' echo "Waiting for another deploy or script run of this project to finish\u2026"',
660
- "fi",
661
- "if ! flock -w 600 9; then",
662
- ' echo "Another deploy or script run of this project has held its lock for 10 minutes." >&2',
663
- " exit 1",
664
- "fi"
665
- ].join(`
666
- `);
667
- }
668
- function renderApplyFiles(layout, incoming) {
669
- return [
670
- `incoming=${shellQuote(incoming)}`,
671
- `files=${shellQuote(layout.fileList)}`,
672
- `code=${shellQuote(layout.code)}`,
673
- 'listed="$incoming.files"',
674
- '(cd "$incoming" && find . \\( -type f -o -type l \\) ! -name .env | LC_ALL=C sort) > "$listed"',
675
- 'mkdir -p "$code"',
676
- 'if [ -f "$files" ]; then',
677
- ' LC_ALL=C comm -23 "$files" "$listed" | while IFS= read -r path; do',
678
- ' rm -f "$code/$path"',
679
- ' dir="$(dirname "$code/$path")"',
680
- ' while [ "$dir" != "$code" ] && [ "$dir" != "$code/." ] && rmdir "$dir" 2>/dev/null; do',
681
- ' dir="$(dirname "$dir")"',
682
- " done",
683
- " done",
684
- "fi",
685
- `(cd "$incoming" && tar -c -f - --exclude=.env .) | (cd "$code" && tar -x -f -)`,
686
- 'mv "$listed" "$files"',
687
- 'rm -rf "$incoming"',
688
- 'find "$(dirname "$incoming")" -mindepth 1 -maxdepth 1 -mmin +1440 -exec rm -rf {} + 2>/dev/null || true'
689
- ].join(`
690
- `);
691
- }
692
- function renderInstallBun(version) {
693
- const release = `https://github.com/oven-sh/bun/releases/download/bun-v${version}`;
694
- return [
695
- 'if [ ! -x "$BUN" ]; then',
696
- ' case "$(uname -m)" in',
697
- " x86_64 | amd64) arch=x64 ;;",
698
- " aarch64 | arm64) arch=aarch64 ;;",
699
- ' *) echo "Bun has no Linux build for $(uname -m)." >&2; exit 1 ;;',
700
- " esac",
701
- ' if [ "$arch" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi',
702
- ' asset="bun-linux-$arch"',
703
- ' download="$(mktemp -d)"',
704
- ` curl -fsSL --retry 3 -o "$download/$asset.zip" ${shellQuote(release)}"/$asset.zip"`,
705
- ` curl -fsSL --retry 3 -o "$download/SHASUMS256.txt" ${shellQuote(release)}/SHASUMS256.txt`,
706
- ' (cd "$download" && grep " $asset.zip\\$" SHASUMS256.txt | sha256sum -c --quiet -)',
707
- ' unzip -q "$download/$asset.zip" -d "$download"',
708
- ' mkdir -p "$BUN_DIR"',
709
- ' mv "$download/$asset/bun" "$BUN"',
710
- ' rm -rf "$download"',
711
- "fi",
712
- 'command -v node > /dev/null || ln -s "$BUN" "$BUN_DIR/node"',
713
- '"$BUN" --version'
714
- ].join(`
715
- `);
716
- }
717
- function renderInstallDependencies() {
718
- return [
719
- 'cd "$PROJECT"',
720
- '"$BUN" install --frozen-lockfile',
721
- "for bin in sixb sixb-deploy-ssh; do",
722
- ' if [ ! -e "$PROJECT/node_modules/.bin/$bin" ]; then',
723
- ' package="@sixb/cli"; [ "$bin" = sixb ] || package="@sixb/deploy-ssh"',
724
- ' echo "$package is not installed. Add it to the project dependencies." >&2',
725
- " exit 1",
726
- " fi",
727
- "done"
728
- ].join(`
729
- `);
730
- }
731
- function runStep(command) {
732
- const program = command.program === "sixb" ? '"$PROJECT/node_modules/.bin/sixb"' : "";
733
- return {
734
- label: [command.program, ...command.args].join(" "),
735
- body: [
736
- 'cd "$PROJECT"',
737
- `"$BUN" ${program} ${command.args.map(shellQuote).join(" ")}`.replace(/ {2,}/g, " ")
738
- ].join(`
739
- `)
740
- };
741
- }
742
- function envStep(command, layout) {
743
- const step = runStep(command);
744
- return { ...step, body: `${step.body} --token-file ${shellQuote(layout.envToken)}` };
745
- }
746
- function renderStopServices() {
747
- return [
748
- 'if systemctl --user is-active --quiet "$UNIT"; then',
749
- ' systemctl --user stop "$UNIT"',
750
- "else",
751
- " echo 'Services were not running.'",
752
- "fi"
753
- ].join(`
754
- `);
755
- }
756
- function renderWriteServices(release, layout) {
757
- return [
758
- writeFileCommand(layout.manifest, `${JSON.stringify(renderProcessManifest(release, layout), null, 2)}
759
- `),
760
- writeFileCommand(layout.ctl, renderCtl(layout)),
761
- 'chmod 755 "$CTL"',
762
- 'mkdir -p "$(dirname "$UNIT_PATH")"',
763
- writeFileCommand(`${layout.unit}.new`, renderUnit(release, layout)),
764
- 'if cmp -s "$UNIT_PATH.new" "$UNIT_PATH"; then',
765
- ' rm -f "$UNIT_PATH.new"',
766
- "else",
767
- ' mv "$UNIT_PATH.new" "$UNIT_PATH"',
768
- " systemctl --user daemon-reload",
769
- ' systemctl --user enable "$UNIT"',
770
- "fi"
771
- ].join(`
772
- `);
420
+ # Progress for the laptop, as RFC 7464 JSON text sequences; a release ends with its exit code.
421
+ event() { printf '\\036{"step":"%s","status":"%s"}\\n' "$1" "$2"; }
422
+ trap 'printf "\\036{\\"exit\\":%d}\\n" "$?"' EXIT
423
+ # \`systemctl --user\` finds the account's systemd through this; SSH sessions usually set it.
424
+ export XDG_RUNTIME_DIR="\${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
425
+
426
+ exec 9> "$root/deploy/lock"
427
+ if ! flock -n 9; then
428
+ echo "Waiting for another deploy or script run of $name to finish\u2026"
429
+ if ! flock -w 600 9; then
430
+ echo "Another deploy or script run of $name has held its lock for 10 minutes." >&2
431
+ exit 1
432
+ fi
433
+ fi
434
+
435
+ event "Prepare release" "running"
436
+ # Unpacking replaces the folder, so it must never be the one that serves.
437
+ if [ "$(readlink "$root/current" 2> /dev/null)" = "releases/$release_id" ]; then
438
+ echo "Release $release_id is the live one. Deploy again to make a new release." >&2
439
+ exit 1
440
+ fi
441
+ rm -rf "$release"
442
+ mkdir -p "$release" "$root/shared"
443
+ (cd "$incoming" && tar -c -f - --exclude=.env .) | (cd "$release" && tar -x -f -)
444
+ chmod 755 "$release"
445
+ mkdir -p "$project"
446
+ # A deployment from before releases kept its \`.env\` in its code folder.
447
+ if [ ! -L "$root/code" ] && [ -f "$root/code/$project_path/.env" ] && [ ! -f "$root/shared/.env" ]; then
448
+ cp -p "$root/code/$project_path/.env" "$root/shared/.env"
449
+ chmod 600 "$root/shared/.env"
450
+ fi
451
+ rm -rf "$incoming"
452
+ # Uploads and logs of deploys long gone.
453
+ find "$root/deploy/incoming" "$root/deploy/runs" -mindepth 1 -maxdepth 1 -mtime +7 -exec rm -rf {} + 2> /dev/null || true
454
+ event "Prepare release" "done"
455
+
456
+ event "Install Bun $bun_version" "running"
457
+ if [ ! -x "$bun" ]; then
458
+ case "$(uname -m)" in
459
+ x86_64 | amd64) arch=x64 ;;
460
+ aarch64 | arm64) arch=aarch64 ;;
461
+ *) echo "Bun has no Linux build for $(uname -m)." >&2; exit 1 ;;
462
+ esac
463
+ # Bun's default x64 build needs AVX2; older CPUs take the baseline build.
464
+ if [ "$arch" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi
465
+ asset="bun-linux-$arch"
466
+ url="https://github.com/oven-sh/bun/releases/download/bun-v$bun_version"
467
+ download="$(mktemp -d)"
468
+ curl -fsSL --retry 3 -o "$download/$asset.zip" "$url/$asset.zip"
469
+ curl -fsSL --retry 3 -o "$download/SHASUMS256.txt" "$url/SHASUMS256.txt"
470
+ (cd "$download" && grep " $asset.zip\\$" SHASUMS256.txt | sha256sum -c --quiet -)
471
+ unzip -q "$download/$asset.zip" -d "$download"
472
+ mkdir -p "$bun_dir"
473
+ mv "$download/$asset/bun" "$bun"
474
+ rm -rf "$download"
475
+ fi
476
+ # Dependency lifecycle scripts call \`node\`; with none installed, Bun runs them.
477
+ command -v node > /dev/null || ln -sf "$bun" "$bun_dir/node"
478
+ "$bun" --version
479
+ event "Install Bun $bun_version" "done"
480
+
481
+ event "Install dependencies" "running"
482
+ cd "$project"
483
+ PATH="$bun_dir:$PATH" "$bun" install --frozen-lockfile --backend=hardlink
484
+ for package in @sixb/cli:sixb @sixb/deploy-ssh:sixb-deploy-ssh; do
485
+ if [ ! -e "node_modules/.bin/\${package#*:}" ]; then
486
+ echo "\${package%%:*} is not installed. Add it to the project's dependencies." >&2
487
+ exit 1
488
+ fi
489
+ done
490
+ if [ ! -e node_modules/@sixb/deploy-ssh/src/server/release.ts ]; then
491
+ echo "This commit's @sixb/deploy-ssh is older than this sixb, which needs its release runner. Upgrade it, or deploy the commit with its own sixb." >&2
492
+ exit 1
493
+ fi
494
+ event "Install dependencies" "done"
495
+
496
+ "$bun" "node_modules/.bin/sixb-deploy-ssh" release "$plan"
497
+ `;
498
+
499
+ // src/plan.ts
500
+ var EVENT_PREFIX = "\x1E";
501
+ function parseEvent(line) {
502
+ if (!line.startsWith(EVENT_PREFIX))
503
+ return null;
504
+ try {
505
+ return JSON.parse(line.slice(EVENT_PREFIX.length));
506
+ } catch {
507
+ return null;
508
+ }
773
509
  }
774
- function renderUpdateRoutes(release, layout) {
510
+ function releaseStepLabels(release) {
775
511
  return [
776
- `new=${shellQuote(`${layout.deployDir}/Caddyfile`)}`,
777
- writeFileCommand(`${layout.deployDir}/Caddyfile`, renderCaddySnippet(release)),
778
- 'if cmp -s "$new" "$CADDY_SNIPPET"; then',
779
- " echo 'Routes unchanged.'",
780
- "else",
781
- ' if [ ! -w "$CADDY_DIR" ]; then',
782
- ' echo "$CADDY_DIR is missing or not writable, so this server is not set up for sixb deploy." >&2',
783
- " exit 1",
784
- " fi",
785
- ' previous="$DEPLOY/Caddyfile.previous"',
786
- ' rm -f "$previous"',
787
- ' if [ -f "$CADDY_SNIPPET" ]; then cp "$CADDY_SNIPPET" "$previous"; fi',
788
- ' cp "$new" "$CADDY_SNIPPET"',
789
- ' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > "$DEPLOY/caddy-validate.log" 2>&1; then',
790
- ' if [ -f "$previous" ]; then cp "$previous" "$CADDY_SNIPPET"; else rm -f "$CADDY_SNIPPET"; fi',
791
- ' tail -n 20 "$DEPLOY/caddy-validate.log" >&2',
792
- " echo 'Caddy rejected the routes; the previous ones are back in place.' >&2",
793
- " exit 1",
794
- " fi",
795
- " sudo -n /usr/bin/systemctl reload caddy",
796
- "fi"
797
- ].join(`
798
- `);
512
+ "Upload source",
513
+ "Prepare release",
514
+ `Install Bun ${release.bunVersion}`,
515
+ "Install dependencies",
516
+ ...release.steps.env ? [commandLabel(release.steps.env)] : [],
517
+ ...release.steps.build.map(commandLabel),
518
+ ...release.steps.beforeStart.map(commandLabel),
519
+ "Start new release",
520
+ "Check services",
521
+ "Update routes",
522
+ "Move singletons",
523
+ "Retire previous release"
524
+ ];
799
525
  }
800
- function renderStartServices() {
801
- return [
802
- 'systemctl --user restart "$UNIT"',
803
- 'systemctl --user is-active --quiet "$UNIT"',
804
- "started=$SECONDS"
805
- ].join(`
806
- `);
526
+ function commandLabel(command) {
527
+ return [command.program, ...command.args].join(" ");
807
528
  }
808
- function renderCheckServices(readinessUrl) {
809
- const waitForApi = readinessUrl ? [
810
- `ready_url=${shellQuote(readinessUrl)}`,
811
- "ready=0",
812
- "for attempt in $(seq 1 90); do",
813
- ` if "$BUN" -e 'const r = await fetch(process.argv[1]).catch(() => null); process.exit(r?.ok ? 0 : 1)' "$ready_url" 2>/dev/null; then`,
814
- " ready=1",
815
- " break",
816
- " fi",
817
- " sleep 1",
818
- "done",
819
- 'if [ "$ready" != 1 ]; then',
820
- ' echo "The API did not answer $ready_url within 90 seconds. Its latest log lines:" >&2',
821
- ' "$CTL" logs api --tail 30 >&2 || true',
822
- " exit 1",
823
- "fi"
824
- ] : [];
825
- return [
826
- ...waitForApi,
827
- "quiet=$((5 - (SECONDS - started)))",
828
- 'if [ "$quiet" -gt 0 ]; then sleep "$quiet"; fi',
829
- '"$CTL" status --check'
830
- ].join(`
831
- `);
529
+ function deriveReleaseId(record) {
530
+ const stamp = record.deployedAt.replace(/[-:.]/g, "").slice(0, 18);
531
+ const sha = record.commit.slice(0, 12).replace(/[^a-zA-Z0-9_-]/g, "");
532
+ return `${stamp}Z-${sha || "release"}`;
832
533
  }
833
534
 
834
535
  // src/server/logs.ts
@@ -840,9 +541,9 @@ function stripTerminalControl(line) {
840
541
  }
841
542
 
842
543
  // src/transport.ts
843
- import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
844
- import { tmpdir as tmpdir2 } from "os";
845
- import { join as join2 } from "path";
544
+ import { mkdtemp, rm } from "fs/promises";
545
+ import { tmpdir } from "os";
546
+ import { join } from "path";
846
547
  class RemoteScriptError extends Error {
847
548
  exitCode;
848
549
  constructor(message, exitCode) {
@@ -861,12 +562,12 @@ class SshShell {
861
562
  this.controlDir = controlDir;
862
563
  }
863
564
  static async open(destination) {
864
- const controlDir = await mkdtemp2(join2(tmpdir2(), "sixb-ssh-"));
565
+ const controlDir = await mkdtemp(join(tmpdir(), "sixb-ssh-"));
865
566
  const shell = new SshShell(destination, controlDir);
866
567
  try {
867
568
  await runProcess(["ssh", ...shell.options(), "-M", "-N", "-f", destination], {});
868
569
  } catch (error) {
869
- await rm2(controlDir, { recursive: true, force: true });
570
+ await rm(controlDir, { recursive: true, force: true });
870
571
  throw sshError(destination, error);
871
572
  }
872
573
  return shell;
@@ -891,7 +592,7 @@ class SshShell {
891
592
  }
892
593
  async close() {
893
594
  await runProcess(["ssh", ...this.options(), "-O", "exit", this.destination], {}).catch(() => {});
894
- await rm2(this.controlDir, { recursive: true, force: true });
595
+ await rm(this.controlDir, { recursive: true, force: true });
895
596
  }
896
597
  options() {
897
598
  return [
@@ -908,7 +609,7 @@ class SshShell {
908
609
  "-o",
909
610
  "LogLevel=ERROR",
910
611
  "-S",
911
- join2(this.controlDir, "control")
612
+ join(this.controlDir, "control")
912
613
  ];
913
614
  }
914
615
  }
@@ -979,71 +680,125 @@ function sshError(destination, error) {
979
680
  }
980
681
  const output = error.message;
981
682
  const host = destination.split("@").at(-1) ?? destination;
982
- const reason = /REMOTE HOST IDENTIFICATION HAS CHANGED/.test(output) ? `${host} answered with a host key other than the one on record. If the server was rebuilt, remove the old key with \`ssh-keygen -R ${host}\` and connect once to accept the new one; for CI, run \`sixb deploy ci\` again. Otherwise, something else is answering at that address: do not deploy to it.` : /Host key verification failed/.test(output) ? `The host key for ${host} is not trusted yet. Connect once with \`ssh ${destination}\`, check the fingerprint, and accept it.` : /Permission denied/.test(output) ? `The server refused your SSH key for ${destination}. Load it into your SSH agent, or ask someone with access to authorize it.` : /Could not resolve hostname/.test(output) ? `${host} does not resolve. Check the target's host.` : /Connection refused|timed out|No route to host/.test(output) ? `Could not reach ${host} over SSH.` : `SSH to ${destination} failed.`;
983
- return new RemoteScriptError(`[SshTarget] ${reason}
683
+ return new RemoteScriptError(`[SshTarget] ${sshFailureReason(output, destination, host)}
984
684
  ${output}`, error.exitCode);
985
685
  }
686
+ function sshFailureReason(output, destination, host) {
687
+ if (/Tailscale SSH requires an additional check/.test(output)) {
688
+ return `Tailscale SSH wants you to sign in again before reaching ${destination}: open the link below, then try again.`;
689
+ }
690
+ if (/tailnet policy does not permit/.test(output)) {
691
+ return `The tailnet's SSH rules don't let you reach ${destination}. Ask a tailnet admin to allow it.`;
692
+ }
693
+ if (/REMOTE HOST IDENTIFICATION HAS CHANGED/.test(output)) {
694
+ return `${host} answered with a host key other than the one on record. If the server was rebuilt, remove the old key with \`ssh-keygen -R ${host}\` and connect once to accept the new one. Otherwise, something else is answering at that address: do not deploy to it.`;
695
+ }
696
+ if (/Host key verification failed/.test(output)) {
697
+ return `The host key for ${host} is not trusted yet. Connect once with \`ssh ${destination}\`, check the fingerprint, and accept it.`;
698
+ }
699
+ if (/Permission denied/.test(output)) {
700
+ return `The server refused your SSH key for ${destination}. Load it into your SSH agent, or ask someone with access to the server to allow it.`;
701
+ }
702
+ if (/Could not resolve hostname/.test(output))
703
+ return `${host} does not resolve. Check the target's host.`;
704
+ if (/Connection refused|timed out|No route to host/.test(output)) {
705
+ return `Could not reach ${host} over SSH.`;
706
+ }
707
+ return `SSH to ${destination} failed.`;
708
+ }
986
709
 
987
710
  // src/operations.ts
988
711
  var NOT_DEPLOYED = "__SIXB_NOT_DEPLOYED__";
989
- async function deployRelease(shell, user, release, source, context) {
990
- const prepared = await capture(shell, renderPrepareScript(release.name, source.commit));
991
- const [home, incoming] = prepared;
992
- if (!home || !incoming) {
712
+ async function deployRelease(shell, release, source, context) {
713
+ const record = {
714
+ commit: source.commit,
715
+ ref: source.ref,
716
+ deployedAt: new Date().toISOString(),
717
+ deployedBy: context.deployedBy
718
+ };
719
+ const releaseId = deriveReleaseId(record);
720
+ const [home, incoming] = await capture(shell, [
721
+ `root="$HOME"/${shellQuote(release.name)}`,
722
+ 'mkdir -p "$root/deploy/incoming" "$root/deploy/runs"',
723
+ 'chmod 700 "$root/deploy/runs"',
724
+ `incoming="$(mktemp -d "$root/deploy/incoming/${releaseId}.XXXXXX")"`,
725
+ 'chmod 755 "$incoming"',
726
+ `printf '%s
727
+ %s
728
+ ' "$HOME" "$incoming"`
729
+ ].join(`
730
+ `));
731
+ if (!home || !incoming)
993
732
  throw new Error("[SshTarget] The server did not report its home directory.");
994
- }
995
- const layout = deploymentLayout({
996
- home,
997
- user,
998
- name: release.name,
999
- projectPath: source.projectPath,
1000
- bunVersion: release.bunVersion
1001
- });
1002
- const { labels, script } = renderDeployScript({
1003
- release,
1004
- layout,
1005
- incoming,
1006
- record: {
1007
- commit: source.commit,
1008
- ref: source.ref,
1009
- deployedAt: new Date().toISOString(),
1010
- deployedBy: context.deployedBy
1011
- }
1012
- });
1013
- context.report({ type: "steps", labels: ["Upload source", ...labels] });
733
+ const labels = releaseStepLabels(release);
734
+ context.report({ type: "steps", labels });
1014
735
  context.report({ type: "step", index: 0, status: "running" });
1015
736
  for (const archive of source.archives) {
1016
- await shell.run(renderReceiveScript(incoming, archive.path), { stdin: archive.open() });
737
+ const directory = archive.path === "." ? incoming : `${incoming}/${archive.path}`;
738
+ await shell.run(`mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`, { stdin: archive.open() });
1017
739
  }
740
+ const runs = `${home}/${release.name}/deploy/runs`;
741
+ const plan = {
742
+ version: 1,
743
+ release,
744
+ record,
745
+ releaseId,
746
+ projectPath: source.projectPath
747
+ };
748
+ const files = { plan: `${runs}/${releaseId}.json`, script: `${runs}/${releaseId}.sh` };
749
+ await upload(shell, files.plan, JSON.stringify(plan));
750
+ await upload(shell, files.script, bootstrap_default);
1018
751
  context.report({ type: "step", index: 0, status: "done" });
1019
- await runReportingSteps(shell, script, context);
752
+ const log = `${runs}/${releaseId}.log`;
753
+ const args = [
754
+ release.name,
755
+ releaseId,
756
+ source.projectPath,
757
+ release.bunVersion,
758
+ incoming,
759
+ files.plan
760
+ ];
761
+ const [pid] = await capture(shell, `setsid nohup bash ${[files.script, ...args].map(shellQuote).join(" ")} > ${shellQuote(log)} 2>&1 < /dev/null & echo $!`);
762
+ await follow(shell, { pid: pid ?? "", log, labels, context });
1020
763
  }
1021
- async function runReportingSteps(shell, script, context) {
1022
- const run = shell.run(script, {
1023
- onLine: (line) => {
1024
- const [marker, index, status] = line.split("\t");
1025
- if (marker === STEP_MARKER && (status === "start" || status === "done")) {
1026
- const step = Number(index) + 1;
1027
- context.report({
1028
- type: "step",
1029
- index: step,
1030
- status: status === "start" ? "running" : "done"
1031
- });
1032
- } else {
1033
- const output = stripTerminalControl(line);
1034
- if (output.trim())
1035
- context.report({ type: "output", line: output });
1036
- }
1037
- }
1038
- });
764
+ async function follow(shell, input) {
765
+ const { context, labels } = input;
766
+ let exit = null;
767
+ let failure = null;
1039
768
  try {
1040
- await run;
769
+ await shell.run(`tail -n +1 -F --pid=${shellQuote(input.pid)} ${shellQuote(input.log)} 2> /dev/null`, {
770
+ onLine: (line, stream) => {
771
+ if (stream !== "stdout")
772
+ return;
773
+ const event = parseEvent(line);
774
+ if (event && "exit" in event) {
775
+ exit = event.exit;
776
+ } else if (event) {
777
+ const index = labels.indexOf(event.step);
778
+ if (index === -1)
779
+ context.report({ type: "output", line: event.step });
780
+ else
781
+ context.report({ type: "step", index, status: event.status });
782
+ } else {
783
+ const output = stripTerminalControl(line);
784
+ if (output.startsWith("[SshTarget] "))
785
+ failure = output;
786
+ if (output.trim())
787
+ context.report({ type: "output", line: output });
788
+ }
789
+ }
790
+ });
1041
791
  } catch (error) {
1042
- if (error instanceof RemoteScriptError && error.exitCode !== 255) {
1043
- throw new Error(`[SshTarget] The step exited with code ${error.exitCode}.`);
1044
- }
1045
- throw error;
792
+ throw new Error(`[SshTarget] Lost the connection while following the deploy, which carries on on the server. \`sixb deploy status\` shows the release once it ends; its log is ${input.log}.`, { cause: error });
1046
793
  }
794
+ if (exit === 0)
795
+ return;
796
+ throw new Error(failure ?? `[SshTarget] The deploy ended with code ${exit ?? "unknown"}.`);
797
+ }
798
+ async function upload(shell, path, content) {
799
+ await shell.run(`umask 077 && cat > ${shellQuote(path)}`, {
800
+ stdin: new Blob([content]).stream()
801
+ });
1047
802
  }
1048
803
  async function readStatus(shell, name) {
1049
804
  const lines = await capture(shell, ctlScript(name, ["status", "--json"], { allowMissing: true }));
@@ -1125,160 +880,6 @@ async function capture(shell, script) {
1125
880
  return lines;
1126
881
  }
1127
882
 
1128
- // src/setup.ts
1129
- import { access } from "fs/promises";
1130
- var PACKAGED_CADDYFILE = "The Caddyfile is an easy way to configure your Caddy web server.";
1131
- function renderAdminScript(input) {
1132
- const user = shellQuote(input.user);
1133
- return [
1134
- "set -euo pipefail",
1135
- `deploy_user=${user}`,
1136
- `public_key=${shellQuote(input.publicKey)}`,
1137
- `admin_login=${shellQuote(input.admin)}`,
1138
- 'step() { printf "\\n== %s\\n" "$1"; }',
1139
- 'quiet() { log="$(mktemp)"; if "$@" > "$log" 2>&1; then rm -f "$log"; else status=$?; tail -n 20 "$log" >&2; rm -f "$log"; return "$status"; fi; }',
1140
- "",
1141
- 'step "Server"',
1142
- "if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then",
1143
- ' echo "sixb deploy needs an Ubuntu or Debian server with systemd." >&2',
1144
- " exit 1",
1145
- "fi",
1146
- '. /etc/os-release && echo "$PRETTY_NAME"',
1147
- "",
1148
- 'step "Packages"',
1149
- "export DEBIAN_FRONTEND=noninteractive",
1150
- 'missing=""',
1151
- "for package in git curl unzip ca-certificates gnupg; do",
1152
- ' dpkg -l "$package" 2> /dev/null | grep -q "^ii" || missing="$missing $package"',
1153
- "done",
1154
- 'if [ -n "$missing" ]; then',
1155
- ' echo "Installing$missing"',
1156
- " quiet apt-get update",
1157
- " quiet apt-get install -y $missing",
1158
- "fi",
1159
- "if ! command -v caddy > /dev/null; then",
1160
- ' echo "Installing caddy"',
1161
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |",
1162
- " gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
1163
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
1164
- " quiet apt-get update",
1165
- " quiet apt-get install -y caddy",
1166
- "fi",
1167
- `echo "git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)"`,
1168
- "",
1169
- 'step "Deploy user $deploy_user"',
1170
- 'id "$deploy_user" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group "$deploy_user"',
1171
- 'home="$(getent passwd "$deploy_user" | cut -d: -f6)"',
1172
- 'chmod 750 "$home"',
1173
- 'install -d -m 0700 -o "$deploy_user" -g "$deploy_user" "$home/.ssh"',
1174
- 'touch "$home/.ssh/authorized_keys"',
1175
- 'grep -qxF "$public_key" "$home/.ssh/authorized_keys" || echo "$public_key" >> "$home/.ssh/authorized_keys"',
1176
- 'chown "$deploy_user:$deploy_user" "$home/.ssh/authorized_keys"',
1177
- 'chmod 0600 "$home/.ssh/authorized_keys"',
1178
- 'loginctl enable-linger "$deploy_user"',
1179
- 'grep -qs XDG_RUNTIME_DIR "$home/.profile" ||',
1180
- ` echo 'export XDG_RUNTIME_DIR="/run/user/$(id -u)"' >> "$home/.profile"`,
1181
- 'chown "$deploy_user:$deploy_user" "$home/.profile"',
1182
- 'if [ "$admin_login" != root ]; then usermod -aG "$deploy_user" "$admin_login"; fi',
1183
- 'echo "$home, key-only, services start at boot"',
1184
- "",
1185
- 'step "Caddy reload"',
1186
- "groupadd -f sixb-deploy",
1187
- 'usermod -aG sixb-deploy "$deploy_user"',
1188
- 'sudoers="$(mktemp)"',
1189
- `echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > "$sudoers"`,
1190
- 'visudo -cf "$sudoers" > /dev/null',
1191
- 'install -m 0440 "$sudoers" /etc/sudoers.d/sixb',
1192
- 'rm -f "$sudoers"',
1193
- 'echo "$deploy_user may run sudo systemctl reload caddy, and nothing else"',
1194
- "",
1195
- 'step "Caddy routes"',
1196
- "caddyfile=/etc/caddy/Caddyfile",
1197
- "backup=/etc/caddy/Caddyfile.before-sixb-deploy",
1198
- "install -d -m 0755 /etc/caddy/sixb.d",
1199
- 'install -d -m 0755 -o "$deploy_user" -g "$deploy_user" "/etc/caddy/sixb.d/$deploy_user"',
1200
- `printf 'import /etc/caddy/sixb.d/%s/*.caddy\\n' "$deploy_user" > "/etc/caddy/sixb.d/$deploy_user.caddy"`,
1201
- "restart_caddy=0",
1202
- `if [ ! -s "$caddyfile" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} "$caddyfile"; then`,
1203
- ' if [ -f "$caddyfile" ]; then cp "$caddyfile" "$backup"; fi',
1204
- ` cat > "$caddyfile" <<'__SIXB_CADDYFILE__'`,
1205
- "# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.",
1206
- "{",
1207
- "\t# Only root and Caddy may change the running configuration.",
1208
- "\tadmin unix//var/lib/caddy/admin.sock",
1209
- "}",
1210
- "",
1211
- "import /etc/caddy/sixb.d/*.caddy",
1212
- "__SIXB_CADDYFILE__",
1213
- " restart_caddy=1",
1214
- `elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' "$caddyfile"; then`,
1215
- ' cp "$caddyfile" "$backup"',
1216
- ` printf '\\n# Routes written by sixb deploy, one folder per deploy user.\\nimport /etc/caddy/sixb.d/*.caddy\\n' >> "$caddyfile"`,
1217
- ` echo "Kept this server's Caddyfile and added one import; the previous one is $backup."`,
1218
- "fi",
1219
- 'if ! caddy validate --config "$caddyfile" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',
1220
- " tail -n 5 /tmp/sixb-caddy-validate.log >&2",
1221
- ' if [ -f "$backup" ]; then cp "$backup" "$caddyfile"; fi',
1222
- ' echo "Caddy rejected the configuration; the previous one is back in place." >&2',
1223
- " exit 1",
1224
- "fi",
1225
- 'if [ "$restart_caddy" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',
1226
- 'echo "/etc/caddy/sixb.d/$deploy_user"',
1227
- "",
1228
- 'step "Checks"',
1229
- "sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&",
1230
- ' echo "Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config." || true',
1231
- "sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&",
1232
- ' echo "Warning: root can log in with a password. Set PermitRootLogin prohibit-password." || true',
1233
- "if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then",
1234
- " for port in 80 443; do",
1235
- ' ufw status | grep -qE "^$port(/tcp)?\\s+ALLOW" ||',
1236
- ' echo "Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp"',
1237
- " done",
1238
- "fi",
1239
- 'echo "Done."'
1240
- ].join(`
1241
- `);
1242
- }
1243
- async function pickPublicKey(input) {
1244
- if (input.key) {
1245
- const path = input.key.endsWith(".pub") ? input.key : `${input.key}.pub`;
1246
- return { text: (await Bun.file(path).text()).trim(), source: path };
1247
- }
1248
- for (const identity of input.identityFiles) {
1249
- const path = `${identity}.pub`;
1250
- if (await access(path).then(() => true, () => false)) {
1251
- return { text: (await Bun.file(path).text()).trim(), source: path };
1252
- }
1253
- }
1254
- const agent = Bun.spawn(["ssh-add", "-L"], { stdout: "pipe", stderr: "ignore" });
1255
- const first = (await new Response(agent.stdout).text()).split(`
1256
- `).find((line) => line.trim());
1257
- if (await agent.exited === 0 && first)
1258
- return { text: first.trim(), source: "your SSH agent" };
1259
- throw new Error("[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`.");
1260
- }
1261
- async function ensureEnvToken(shell, name, createToken) {
1262
- const path = `"$HOME"/${shellQuote(`${name}/${ENV_TOKEN_FILE}`)}`;
1263
- const installed = await shell.run(`[ -s ${path} ]`).then(() => true, (error) => {
1264
- if (error instanceof RemoteScriptError && error.exitCode === 1)
1265
- return false;
1266
- throw error;
1267
- });
1268
- if (installed)
1269
- return false;
1270
- await shell.run([
1271
- "set -e",
1272
- "umask 077",
1273
- `mkdir -p "$HOME"/${shellQuote(name)}`,
1274
- `cat > ${path}.new`,
1275
- `mv ${path}.new ${path}`
1276
- ].join(`
1277
- `), { stdin: new Blob([`${await createToken()}
1278
- `]).stream() });
1279
- return true;
1280
- }
1281
-
1282
883
  // src/ssh-config.ts
1283
884
  import { homedir } from "os";
1284
885
  async function resolveSshConfig(destination) {
@@ -1308,40 +909,40 @@ async function resolveSshConfig(destination) {
1308
909
  }
1309
910
 
1310
911
  // src/ssh-target.ts
1311
- var OPTIONS = ["host", "user", "ports"];
1312
912
  var DEFAULT_USER = "sixb";
1313
- var DEFAULT_PORTS = {
1314
- app: 3001,
1315
- api: 3002
913
+ var REMOVED_OPTIONS = {
914
+ ports: "a server runs one deployment, on fixed ports",
915
+ standbyPorts: "a server runs one deployment, on fixed ports"
1316
916
  };
1317
- var LISTEN_HOST = "127.0.0.1";
1318
917
  var USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/;
918
+ var LISTEN_HOST = "127.0.0.1";
1319
919
 
1320
920
  class SshTarget {
1321
921
  kind = "ssh";
1322
922
  host;
1323
923
  user;
1324
924
  location;
1325
- #ports;
1326
925
  constructor(options) {
1327
926
  if (typeof options !== "object" || options === null) {
1328
927
  throw new Error('[SshTarget] Pass options, such as `new SshTarget({ host: "203.0.113.10" })`.');
1329
928
  }
1330
929
  for (const key of Object.keys(options)) {
1331
- if (!OPTIONS.includes(key)) {
1332
- throw new Error(`[SshTarget] Unknown option '${key}'. Available: ${OPTIONS.join(", ")}.`);
930
+ const removed = REMOVED_OPTIONS[key];
931
+ if (removed)
932
+ throw new Error(`[SshTarget] Remove \`${key}\`: ${removed}.`);
933
+ if (key !== "host" && key !== "user") {
934
+ throw new Error(`[SshTarget] Unknown option '${key}'. Available: host, user.`);
1333
935
  }
1334
936
  }
1335
937
  this.host = validateHost(options.host);
1336
938
  this.user = validateUser(options.user ?? DEFAULT_USER);
1337
939
  this.location = `${this.user}@${this.host}`;
1338
- this.#ports = { ...DEFAULT_PORTS, ...validatePorts(options.ports) };
1339
940
  }
1340
941
  listenAddress(service) {
1341
- return { host: LISTEN_HOST, port: this.#ports[service] };
942
+ return { host: LISTEN_HOST, port: SLOT_PORTS.blue[service] };
1342
943
  }
1343
944
  deploy(release, source, context) {
1344
- return this.#connected((shell) => deployRelease(shell, this.user, release, source, context));
945
+ return this.#connected((shell) => deployRelease(shell, release, source, context));
1345
946
  }
1346
947
  status(context) {
1347
948
  return this.#connected((shell) => readStatus(shell, context.name));
@@ -1363,12 +964,12 @@ class SshTarget {
1363
964
  try {
1364
965
  server = await this.#connected(async (shell) => [
1365
966
  { id: "ssh", label: "SSH", status: "ok", detail: this.location },
1366
- ...await runChecks(shell, {
967
+ ...await checkHost(shell, {
1367
968
  name: context.name,
1368
969
  projectPath: context.projectPath,
1369
- ports: release.services.flatMap((service) => service.http ? [{ service: service.name, port: service.http.port }] : []),
1370
- envFromSource: release.steps.env !== undefined,
1371
- location: this.location
970
+ ports: [...Object.values(SLOT_PORTS.blue), ...Object.values(SLOT_PORTS.green)],
971
+ settings: release.steps.env === undefined ? "env-file" : context.envToken ? "env-token" : "identity",
972
+ chromium: context.chromium
1372
973
  })
1373
974
  ]);
1374
975
  } catch (error) {
@@ -1376,69 +977,6 @@ class SshTarget {
1376
977
  }
1377
978
  return [...server, ...await dns];
1378
979
  }
1379
- async setup(release, context) {
1380
- const before = await this.check(release, context);
1381
- const serverFixes = before.filter((check) => check.status === "fixable" && check.id !== "project.env" && check.id !== ENV_TOKEN_CHECK || check.id === "ssh" && check.status !== "ok");
1382
- const unreachable = before.find((check) => check.id === "ssh" && check.status === "manual");
1383
- if (unreachable) {
1384
- throw new Error(`[SshTarget] ${unreachable.detail}`);
1385
- }
1386
- if (serverFixes.length > 0) {
1387
- const admin = context.admin ?? "root";
1388
- const { identityFiles } = await resolveSshConfig(this.location);
1389
- const key = await pickPublicKey({ key: context.key, identityFiles });
1390
- context.write(`Setting up ${this.host} as ${admin}, authorizing ${key.source} for ${this.user}.`);
1391
- await runAsAdmin(`${admin}@${this.host}`, admin === "root", renderAdminScript({ user: this.user, publicKey: key.text, admin }));
1392
- }
1393
- context.write(`Preparing ${context.name} as ${this.user}.`);
1394
- await this.#connected((shell) => shell.run([
1395
- `project="$HOME"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,
1396
- 'mkdir -p "$project"',
1397
- 'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi',
1398
- `token="$HOME"/${shellQuote(`${context.name}/${ENV_TOKEN_FILE}`)}`,
1399
- 'if [ -f "$token" ]; then chmod 600 "$token"; fi'
1400
- ].join(`
1401
- `)));
1402
- const { createEnvToken } = context;
1403
- if (release.steps.env && createEnvToken) {
1404
- const installed = await this.#connected((shell) => ensureEnvToken(shell, context.name, createEnvToken));
1405
- if (installed)
1406
- context.write(`Installed a read-only token for ${context.name}.`);
1407
- }
1408
- }
1409
- access = {
1410
- list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),
1411
- add: (key) => this.#connected((shell) => addKey(shell, key)).then(withoutLine),
1412
- remove: (match) => this.#connected(async (shell) => (await removeKeys(shell, match)).map(withoutLine))
1413
- };
1414
- ci = {
1415
- create: (job, context) => this.#createCiKey(job, context.name)
1416
- };
1417
- async#createCiKey(job, name) {
1418
- const ssh = await resolveSshConfig(this.location);
1419
- if (ssh.proxyJump) {
1420
- throw new Error(`[SshTarget] Your SSH config reaches ${this.host} through ${ssh.proxyJump}, and CI connects ` + "directly. Set `host` to an address CI can reach.");
1421
- }
1422
- const comment = `sixb-ci:${name}@${job}`;
1423
- const pair = await generateCiKey(comment);
1424
- const { key, hostKeys } = await this.#connected(async (shell) => ({
1425
- hostKeys: await readHostKeys(shell),
1426
- key: await addKey(shell, pair.publicKey, "restrict")
1427
- }));
1428
- return {
1429
- description: `${key.fingerprint} for ${this.location}, restricted to running commands`,
1430
- secrets: {
1431
- SIXB_DEPLOY_SSH_KEY: pair.privateKey,
1432
- SIXB_DEPLOY_KNOWN_HOSTS: knownHostsLines(hostKeys, ssh.hostname, ssh.port).join(`
1433
- `)
1434
- },
1435
- install: renderCiInstall({ host: this.host, hostname: ssh.hostname, port: ssh.port }),
1436
- retireOthers: () => this.#connected(async (shell) => (await removeKeysWhere(shell, (other) => other.comment === comment && other.fingerprint !== key.fingerprint)).map(withoutLine)),
1437
- revoke: () => this.#connected(async (shell) => {
1438
- await removeKeysWhere(shell, (other) => other.fingerprint === key.fingerprint);
1439
- })
1440
- };
1441
- }
1442
980
  async#connected(work) {
1443
981
  const shell = await SshShell.open(this.location);
1444
982
  try {
@@ -1448,13 +986,22 @@ class SshTarget {
1448
986
  }
1449
987
  }
1450
988
  }
989
+ function validateUser(value) {
990
+ if (value === "root") {
991
+ throw new Error("[SshTarget] Deployments never run as root. Use an account without sudo.");
992
+ }
993
+ if (typeof value !== "string" || !USER_PATTERN.test(value)) {
994
+ throw new Error(`[SshTarget] user ${JSON.stringify(value)} is not a Linux account name. Use lowercase ` + "letters, digits, underscores and hyphens, starting with a letter or underscore.");
995
+ }
996
+ return value;
997
+ }
1451
998
  function validateHost(value) {
1452
999
  if (typeof value !== "string" || value.trim() === "") {
1453
1000
  throw new Error("[SshTarget] host must be the server's hostname or IP address.");
1454
1001
  }
1455
1002
  const host = value.trim();
1456
1003
  if (host.includes("@")) {
1457
- throw new Error(`[SshTarget] host '${host}' includes a user. Set the host alone, and the user with \`user\`.`);
1004
+ throw new Error(`[SshTarget] host '${host}' includes a user. Set the host alone, and the account with \`user\`.`);
1458
1005
  }
1459
1006
  if (host.startsWith("-") || /[\s/\\]/.test(host)) {
1460
1007
  throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`);
@@ -1464,68 +1011,18 @@ function validateHost(value) {
1464
1011
  }
1465
1012
  return host;
1466
1013
  }
1467
- function validateUser(value) {
1468
- if (value === "root") {
1469
- throw new Error("[SshTarget] Deployments never run as root. Use a deploy user without sudo, such as the " + 'default "sixb".');
1470
- }
1471
- if (typeof value !== "string" || !USER_PATTERN.test(value)) {
1472
- throw new Error(`[SshTarget] user ${JSON.stringify(value)} is not a Linux user name. Use lowercase ` + "letters, digits, underscores, and hyphens, starting with a letter or underscore.");
1473
- }
1474
- return value;
1475
- }
1476
- function validatePorts(value) {
1477
- if (value === undefined)
1478
- return {};
1479
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1480
- throw new Error("[SshTarget] ports must be an object, such as `{ api: 3012 }`.");
1481
- }
1482
- const ports = {};
1483
- for (const [service, port] of Object.entries(value)) {
1484
- if (!Object.hasOwn(DEFAULT_PORTS, service)) {
1485
- throw new Error(`[SshTarget] ports.${service} is not an HTTP service. Available: api, app.`);
1486
- }
1487
- if (!Number.isInteger(port) || port < 1024 || port > 65535) {
1488
- throw new Error(`[SshTarget] ports.${service} must be a port from 1024 to 65535.`);
1489
- }
1490
- ports[service] = port;
1491
- }
1492
- return ports;
1493
- }
1494
1014
  function sshCheck(location, error) {
1495
- const message = (error instanceof Error ? error.message : String(error)).split(`
1496
- `)[0]?.replace(/^\[SshTarget\] /, "") ?? "";
1497
- if (error instanceof RemoteScriptError && /refused your SSH key/.test(message)) {
1498
- return {
1499
- id: "ssh",
1500
- label: "SSH",
1501
- status: "fixable",
1502
- detail: message,
1503
- remedy: `Run \`sixb deploy setup --admin <login>\` with a login that has sudo: it creates the deploy user and authorizes your key. Or have someone with access run \`sixb deploy access add\` with your key.`
1504
- };
1505
- }
1015
+ const [message = ""] = (error instanceof Error ? error.message : String(error)).split(`
1016
+ `);
1506
1017
  return {
1507
1018
  id: "ssh",
1508
1019
  label: "SSH",
1509
- status: "manual",
1510
- detail: message || `Cannot reach ${location}.`
1020
+ status: "fail",
1021
+ detail: message.replace(/^\[SshTarget\] /, "") || `Cannot reach ${location}.`
1511
1022
  };
1512
1023
  }
1513
- function withoutLine({ type, fingerprint, comment, restricted }) {
1514
- return { type, fingerprint, comment, restricted };
1515
- }
1516
- async function runAsAdmin(destination, root, script) {
1517
- const command = `${root ? "" : "sudo "}bash -c ${shellQuote(script)}`;
1518
- const ssh = ["ssh", "-tt", "-o", "ConnectTimeout=15", "-o", "LogLevel=ERROR"];
1519
- const child = Bun.spawn([...ssh, destination, command], {
1520
- stdio: ["inherit", "inherit", "inherit"]
1521
- });
1522
- const exitCode = await child.exited;
1523
- if (exitCode !== 0) {
1524
- throw new Error(`[SshTarget] Setting up the server as ${destination} failed (exit code ${exitCode}).`);
1525
- }
1526
- }
1527
1024
  export {
1528
1025
  SshTarget
1529
1026
  };
1530
1027
 
1531
- //# debugId=B4A600CC24E47FE664756E2164756E21
1028
+ //# debugId=EFD7A0BD5214D5D664756E2164756E21