@sixb/deploy-ssh 0.2.6 → 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 -44
  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 -1527
  7. package/dist/index.js.map +10 -16
  8. package/dist/layout.d.ts +87 -30
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -3
  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 +15 -11
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +10 -4
  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 +0 -4
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +8 -8
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -24
  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 +109 -61
  35. package/src/operations.ts +105 -65
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +54 -35
  38. package/src/server/cli.ts +16 -20
  39. package/src/server/manifest.ts +13 -6
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +1 -5
  43. package/src/server/supervisor.ts +45 -238
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +43 -285
  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 -48
  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 -257
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -703
  64. package/src/setup.ts +0 -203
package/dist/index.js CHANGED
@@ -2,374 +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);
98
- }
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}`] : []
99
87
  });
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);
103
- return {
104
- lines,
105
- keys: lines.flatMap((line) => parseAuthorizedKey(line) ?? []),
106
- hash: sha256(content)
107
- };
108
88
  }
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
- `));
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
+ });
127
124
  }
128
- function sha256(content) {
129
- return createHash2("sha256").update(content).digest("hex");
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
+ });
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`] : []
150
+ });
130
151
  }
131
-
132
- // src/check.ts
133
- import { resolve4, resolve6 } from "dns/promises";
134
- import { isIP } from "net";
135
- import { posix as posix2 } from "path";
136
-
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 releasesDir = posix.join(root, "releases");
143
- const currentLink = posix.join(root, "current");
144
- const code = posix.join(root, "code");
145
- const sharedDir = posix.join(root, "shared");
146
- const deployDir = posix.join(root, "deploy");
147
- const runDir = posix.join(root, "run");
148
- const bunDir = posix.join(input.home, ".sixb", "bun", input.bunVersion);
149
- const unitName = `sixb-${input.name}.service`;
150
- const caddyDir = posix.join("/etc/caddy/sixb.d", input.user);
151
- return {
152
- root,
153
- releasesDir,
154
- currentLink,
155
- code,
156
- sharedDir,
157
- sharedEnv: posix.join(sharedDir, ".env"),
158
- envToken: posix.join(root, ENV_TOKEN_FILE),
159
- project: posix.join(code, input.projectPath),
160
- projectPath: input.projectPath,
161
- deployDir,
162
- incomingDir: posix.join(deployDir, "incoming"),
163
- lock: posix.join(deployDir, "lock"),
164
- fileList: posix.join(deployDir, "files.txt"),
165
- manifest: posix.join(deployDir, "processes.json"),
166
- candidateManifest: posix.join(deployDir, "candidate.json"),
167
- releaseRecord: posix.join(deployDir, "release.json"),
168
- ctl: posix.join(deployDir, "ctl"),
169
- runDir,
170
- logDir: posix.join(runDir, "logs"),
171
- bunDir,
172
- bun: posix.join(bunDir, "bun"),
173
- unitName,
174
- unit: posix.join(input.home, ".config", "systemd", "user", unitName),
175
- caddyDir,
176
- caddySnippet: posix.join(caddyDir, `${input.name}.caddy`)
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."
177
171
  };
178
172
  }
179
- function releaseLayout(layout, releaseId) {
180
- const root = posix.join(layout.releasesDir, releaseId);
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 ?? [];
181
178
  return {
182
- id: releaseId,
183
- root,
184
- project: posix.join(root, layout.projectPath)
179
+ id,
180
+ label,
181
+ status: "fail",
182
+ detail,
183
+ remedy: fix.remedy ?? `See ${HOST_REQUIREMENTS}.`,
184
+ ...commands.length > 0 ? { commands } : {}
185
185
  };
186
186
  }
187
+ function pasteable(value) {
188
+ return value && /^[A-Za-z0-9._/-]+$/.test(value) ? value : null;
189
+ }
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;
208
+ }
209
+
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.
216
+
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; }
187
219
 
188
- // src/check.ts
189
- var CHECK_MARKER = "__SIXB_CHECK__";
190
- var TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"];
191
- var ENV_TOKEN_CHECK = "project.env-token";
192
- function renderCheckScript(input) {
193
- const project = posix2.join(input.name, "code", input.projectPath);
194
- const sharedEnv = posix2.join(input.name, "shared", ".env");
195
- const envToken = posix2.join(input.name, ENV_TOKEN_FILE);
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")"
244
+
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) {
196
324
  return [
197
- `emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
198
- `project="$HOME"/${shellQuote(project)}`,
199
- `shared_env="$HOME"/${shellQuote(sharedEnv)}`,
200
- `manifest="$HOME"/${shellQuote(input.name)}/deploy/processes.json`,
201
- `ports_file="$HOME"/${shellQuote(input.name)}/deploy/ports.txt`,
202
- 'routes_dir="/etc/caddy/sixb.d/$USER"',
203
- `snippet="$routes_dir"/${shellQuote(`${input.name}.caddy`)}`,
204
- "",
205
- "if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then",
206
- ' emit server.os ok "$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',
207
- "else",
208
- ' emit server.os manual "$(uname -s) without apt and systemd"',
209
- "fi",
210
- "",
211
- 'missing=""',
212
- `for tool in ${TOOLS.join(" ")}; do command -v "$tool" > /dev/null || missing="$missing $tool"; done`,
213
- 'if [ -n "$missing" ]; then emit server.tools fixable "missing:$missing"',
214
- 'else emit server.tools ok "Caddy $(caddy version 2>/dev/null | cut -d" " -f1), git, curl, unzip"; fi',
215
- "",
216
- "if command -v caddy > /dev/null; then",
217
- ' caddy_version="$(caddy version 2>/dev/null | cut -d" " -f1 | sed "s/^v//")"',
218
- ' if [ "$(printf "%s\\n" 2.7.0 "$caddy_version" | sort -V | head -n 1)" = 2.7.0 ]; then emit server.caddy ok "$caddy_version"',
219
- ' else emit server.caddy manual "$caddy_version is older than 2.7"; fi',
220
- "fi",
221
- "",
222
- 'if [ -e "/var/lib/systemd/linger/$USER" ]; then emit server.linger ok "on for $USER"',
223
- 'else emit server.linger fixable "off for $USER: services would stop when you log out"; fi',
224
- "",
225
- "if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
226
- ' emit server.reload ok "$USER may reload Caddy"',
227
- "else",
228
- ' emit server.reload fixable "$USER may not run sudo systemctl reload caddy"',
229
- "fi",
230
- "",
231
- 'problems=""',
232
- '[ -d "$routes_dir" ] && [ -w "$routes_dir" ] || problems="$problems; $routes_dir is missing or not writable"',
233
- 'grep -qsF "import $routes_dir/*.caddy" "/etc/caddy/sixb.d/$USER.caddy" || problems="$problems; /etc/caddy/sixb.d/$USER.caddy does not import it"',
234
- `grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems="$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy"`,
235
- 'if [ -z "$problems" ]; then emit server.routes ok "$routes_dir"',
236
- `else emit server.routes fixable "$(printf '%s' "$problems" | sed 's/^; //')"; fi`,
237
- "",
238
- "if ss -ltnH 2> /dev/null | grep -qE '(127\\.0\\.0\\.1|\\[::1\\]):2019 '; then",
239
- ` emit server.admin-api warning "Caddy's admin API listens on localhost:2019, where any process on the server can change every route"`,
240
- "else",
241
- ' emit server.admin-api ok "not on localhost:2019"',
242
- "fi",
243
- "",
244
- ...input.envFromSource ? [
245
- `token="$HOME"/${shellQuote(envToken)}`,
246
- `if [ ! -s "$token" ]; then emit ${ENV_TOKEN_CHECK} fixable "$token has no token"`,
247
- `elif [ "$(stat -c %a "$token")" != 600 ]; then emit ${ENV_TOKEN_CHECK} fixable "$token is readable by others (mode $(stat -c %a "$token"))"`,
248
- `else emit ${ENV_TOKEN_CHECK} ok "$token"; fi`
249
- ] : [
250
- 'env_file="$project/.env"',
251
- 'if [ -f "$shared_env" ]; then env_file="$shared_env"; fi',
252
- 'if [ ! -f "$env_file" ]; then emit project.env manual "$env_file does not exist"',
253
- 'elif [ "$(stat -c %a "$env_file")" != 600 ]; then emit project.env fixable "$env_file is readable by others (mode $(stat -c %a "$env_file"))"',
254
- 'else emit project.env ok "$env_file"; fi'
255
- ],
256
- "",
257
- ...input.ports.flatMap(({ service, port }) => [
258
- `if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
259
- ` if grep -qx '${port}' "$ports_file" 2> /dev/null || { grep -qs '"--port",' "$manifest" && grep -A1 -s '"--port",' "$manifest" | grep -q '"${port}"'; }; then`,
260
- ` emit project.port.${service} ok "${port}, used by this deployment"`,
261
- " else",
262
- ` emit project.port.${service} manual "${port} is in use by another program"`,
263
- " fi",
264
- `elif grep -ls '127.0.0.1:${port}\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv "^$snippet$"; then`,
265
- ` emit project.port.${service} manual "${port} is routed to another deployment"`,
266
- `elif grep -lxs '${port}' "$HOME"/*/deploy/ports.txt 2> /dev/null | grep -qv "^$ports_file$"; then`,
267
- ` emit project.port.${service} manual "${port} is reserved by another deployment"`,
268
- "else",
269
- ` emit project.port.${service} ok "${port}"`,
270
- "fi"
271
- ]),
272
- "",
273
- `free_kb="$(df -Pk "$HOME" | awk 'NR == 2 { print $4 + 0 }')"`,
274
- 'if [ "$free_kb" -lt 2097152 ]; then emit server.disk warning "$((free_kb / 1024)) MB free"',
275
- '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
276
330
  ].join(`
277
331
  `);
278
332
  }
279
- function parseCheckOutput(lines, context) {
280
- return lines.flatMap((line) => {
281
- const [marker, id, status, detail] = line.split("\t");
282
- if (marker !== CHECK_MARKER || !id || !isStatus(status))
283
- return [];
284
- return [describe(id, status, detail ?? "", context)];
285
- });
286
- }
287
333
  async function checkDns(release, hostname) {
288
- 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));
289
336
  return Promise.all(release.services.flatMap((service) => {
290
- const http = service.http;
291
- if (!http)
337
+ const domain = service.http?.domain;
338
+ if (!domain)
292
339
  return [];
293
340
  return [
294
341
  (async () => {
295
- const found = await lookup(http.domain);
342
+ const found = await lookup(domain);
296
343
  const id = `dns.${service.name}`;
297
344
  const label = `${service.name} DNS`;
298
- if (expected.length > 0 && found.some((address) => expected.includes(address))) {
299
- 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
+ };
300
354
  }
301
- const target = expected[0] ?? hostname;
355
+ if (!comparable || found.some((address) => server.includes(address))) {
356
+ return { id, label, status: "ok", detail };
357
+ }
358
+ const target = server[0] ?? hostname;
302
359
  return {
303
360
  id,
304
361
  label,
305
362
  status: "warning",
306
- detail: found.length > 0 ? `${http.domain} \u2192 ${found.join(", ")}` : `${http.domain} does not resolve`,
307
- 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.`
308
365
  };
309
366
  })()
310
367
  ];
311
368
  }));
312
369
  }
313
- async function runChecks(shell, input) {
314
- const lines = [];
315
- await shell.run(renderCheckScript(input), {
316
- onLine: (line, stream) => {
317
- if (stream === "stdout")
318
- lines.push(line);
319
- }
320
- });
321
- return parseCheckOutput(lines, input);
322
- }
323
- var LABELS = {
324
- "server.os": "Server",
325
- "server.tools": "Server tools",
326
- "server.linger": "Services at boot",
327
- "server.caddy": "Caddy version",
328
- "server.reload": "Caddy reload",
329
- "server.routes": "Caddy routes",
330
- "server.admin-api": "Caddy admin API",
331
- "server.disk": "Disk space",
332
- "project.env": ".env",
333
- [ENV_TOKEN_CHECK]: "Source token"
334
- };
335
- function describe(id, status, detail, context) {
336
- const label = LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13).replace(/-/g, " ")} port` : id);
337
- const check = { id, label, status, detail };
338
- if (status === "ok")
339
- return check;
340
- if (status === "fixable")
341
- return { ...check, remedy: "Run `sixb deploy setup`." };
342
- if (id === "server.os")
343
- return { ...check, remedy: "Deploy to an Ubuntu or Debian server." };
344
- if (id === "project.env") {
345
- const path = detail.replace(/ does not exist$/, "");
346
- return {
347
- ...check,
348
- remedy: `Create it with the project's settings: \`ssh ${context.location} 'install -m 600 /dev/null ${path}'\`, then edit it.`
349
- };
350
- }
351
- if (id.startsWith("project.port.")) {
352
- return {
353
- ...check,
354
- remedy: "Give this service another port in the target's `ports` or `standbyPorts`."
355
- };
356
- }
357
- if (id === "server.caddy") {
358
- return {
359
- ...check,
360
- remedy: "Upgrade Caddy from its own apt repository: https://caddyserver.com/docs/install#debian-ubuntu-raspbian"
361
- };
362
- }
363
- if (id === "server.admin-api") {
364
- return {
365
- ...check,
366
- remedy: "Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile."
367
- };
368
- }
369
- return check;
370
- }
371
- function isStatus(value) {
372
- 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;
373
375
  }
374
376
  async function lookup(hostname) {
375
377
  const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))]);
@@ -389,840 +391,159 @@ async function settle(query) {
389
391
  }
390
392
  }
391
393
 
392
- // src/ci.ts
393
- import { mkdtemp, readFile, rm } from "fs/promises";
394
- import { tmpdir } from "os";
395
- import { join } from "path";
396
- async function generateCiKey(comment) {
397
- const dir = await mkdtemp(join(tmpdir(), "sixb-ci-key-"));
398
- try {
399
- const path = join(dir, "key");
400
- const child = Bun.spawn(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", path], {
401
- stdin: "ignore",
402
- stdout: "ignore",
403
- stderr: "pipe"
404
- });
405
- if (await child.exited !== 0) {
406
- const reason = (await new Response(child.stderr).text()).trim();
407
- throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`);
408
- }
409
- return {
410
- privateKey: await readFile(path, "utf8"),
411
- publicKey: (await readFile(`${path}.pub`, "utf8")).trim()
412
- };
413
- } finally {
414
- await rm(dir, { recursive: true, force: true });
415
- }
416
- }
417
- async function readHostKeys(shell) {
418
- const keys = [];
419
- await shell.run("cat /etc/ssh/ssh_host_*_key.pub", {
420
- onLine: (line, stream) => {
421
- const [type, key] = line.trim().split(/\s+/);
422
- if (stream === "stdout" && type && key)
423
- keys.push(`${type} ${key}`);
424
- }
425
- });
426
- if (keys.length === 0)
427
- throw new Error("[SshTarget] Could not read the server's SSH host keys.");
428
- return keys;
429
- }
430
- function knownHostsLines(hostKeys, hostname, port) {
431
- const name = port === 22 ? hostname : `[${hostname}]:${port}`;
432
- return hostKeys.map((key) => `${name} ${key}`);
433
- }
434
- function renderCiInstall(input) {
435
- return [
436
- "install -d -m 700 ~/.ssh",
437
- "install -m 600 /dev/null ~/.ssh/sixb_deploy",
438
- `printf '%s\\n' "$SIXB_DEPLOY_SSH_KEY" > ~/.ssh/sixb_deploy`,
439
- `printf '%s\\n' "$SIXB_DEPLOY_KNOWN_HOSTS" > ~/.ssh/sixb_known_hosts`,
440
- "cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'",
441
- `Host ${input.host}`,
442
- ` HostName ${input.hostname}`,
443
- ` Port ${input.port}`,
444
- " IdentityFile ~/.ssh/sixb_deploy",
445
- " IdentitiesOnly yes",
446
- " UserKnownHostsFile ~/.ssh/sixb_known_hosts",
447
- " StrictHostKeyChecking yes",
448
- "__SIXB_SSH_CONFIG__"
449
- ];
450
- }
394
+ // src/layout.ts
395
+ var SLOT_PORTS = {
396
+ blue: { app: 3001, api: 3002 },
397
+ green: { app: 3011, api: 3012 }
398
+ };
451
399
 
452
400
  // src/operations.ts
453
401
  import { randomUUID } from "crypto";
454
402
 
455
- // src/server/logs.ts
456
- var MAX_LOG_BYTES = 20 * 1024 * 1024;
457
- var RECENT_BYTES = 256 * 1024;
458
- var TERMINAL_CONTROL = /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[@-Z\\-_])/g;
459
- function stripTerminalControl(line) {
460
- return line.replace(TERMINAL_CONTROL, "");
461
- }
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>
462
410
 
463
- // src/server/supervisor.ts
464
- var RETIRING_KILL_TIMEOUT_MS = 300000;
465
- var INTERRUPT_LEAD_MS = 1e4;
466
- function retiringKillTimeoutMs(killTimeoutMs) {
467
- return Math.max(killTimeoutMs, RETIRING_KILL_TIMEOUT_MS);
468
- }
411
+ set -euo pipefail
412
+ name=$1 release_id=$2 project_path=$3 bun_version=$4 incoming=$5 plan=$6
469
413
 
470
- // src/update-page.ts
471
- function renderUpdatePage() {
472
- return `<!doctype html>
473
- <html lang="en">
474
- <head>
475
- <meta charset="utf-8">
476
- <meta name="viewport" content="width=device-width, initial-scale=1">
477
- <meta http-equiv="refresh" content="10">
478
- <title>Updates in progress</title>
479
- <style>
480
- :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; }
481
- * { box-sizing: border-box; }
482
- body { margin: 0; min-height: 100vh; min-height: 100svh; display: grid; place-items: center; padding: 48px 28px; -webkit-font-smoothing: antialiased; }
483
- main { width: 100%; max-width: 480px; }
484
- .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; }
485
- .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; }
486
- 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; }
487
- .description { margin: 0; max-width: 380px; color: var(--muted); font-size: 15px; line-height: 1.8; text-wrap: pretty; }
488
- .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); }
489
- .footer p { margin: 0; font-size: 12px; line-height: 1.6; }
490
- .footer .interval { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; letter-spacing: 0.02em; }
491
- @keyframes spin { to { transform: rotate(360deg); } }
492
- @media (prefers-reduced-motion: reduce) { .loader { animation: none; } }
493
- @media (prefers-color-scheme: dark) {
494
- :root { background: #0a0a0a; color: #f5f5f5; --muted: #999; --line: #262626; --surface: #111; --track: #444; }
495
- }
496
- </style>
497
- </head>
498
- <body>
499
- <main>
500
- <div class="status"><span class="loader" aria-hidden="true"></span>Site update</div>
501
- <h1>Updates in progress</h1>
502
- <p class="description">We\u2019re making a few updates. The site should be back soon. Thanks for your patience.</p>
503
- <div class="footer">
504
- <p>This page will reconnect automatically.</p>
505
- <p class="interval">Retrying every 10s</p>
506
- </div>
507
- </main>
508
- </body>
509
- </html>`;
510
- }
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"
511
419
 
512
- // src/render.ts
513
- var GENERATED = "Generated by sixb deploy. Changes are replaced on the next deploy.";
514
- function releaseForSlot(release, ports) {
515
- return {
516
- ...release,
517
- services: release.services.map((service) => {
518
- if (!service.http || service.name !== "api" && service.name !== "app") {
519
- return service;
520
- }
521
- const port = ports[service.name];
522
- return {
523
- ...service,
524
- command: {
525
- ...service.command,
526
- args: replacePortArg(service.command.args, port)
527
- },
528
- http: {
529
- ...service.http,
530
- port
531
- }
532
- };
533
- })
534
- };
535
- }
536
- function replacePortArg(args, port) {
537
- const next = [...args];
538
- const index = next.indexOf("--port");
539
- if (index !== -1 && index + 1 < next.length) {
540
- next[index + 1] = String(port);
541
- }
542
- return next;
543
- }
544
- function renderProcessManifest(release, layout, options = {}) {
545
- const projectDir = options.projectDir ?? layout.project;
546
- const sixb = `${projectDir}/node_modules/.bin/sixb`;
547
- return {
548
- version: 1,
549
- name: release.name,
550
- ...options.slot ? { slot: options.slot } : {},
551
- cwd: projectDir,
552
- runDir: layout.runDir,
553
- logDir: layout.logDir,
554
- releasePath: layout.releaseRecord,
555
- env: release.env,
556
- services: release.services.map((service) => ({
557
- name: service.name,
558
- kind: service.kind,
559
- processName: `${release.name}-${service.name}`,
560
- command: layout.bun,
561
- args: service.command.program === "sixb" ? [sixb, ...service.command.args] : [...service.command.args],
562
- env: serviceEnvWithDrain(service),
563
- instances: service.instances,
564
- killTimeoutMs: service.process.killTimeoutMs,
565
- restartDelayMs: service.process.restartDelayMs,
566
- ...service.process.maxMemory ? { maxMemory: service.process.maxMemory } : {}
567
- }))
568
- };
569
- }
570
- function serviceEnvWithDrain(service) {
571
- if ((service.name === "api" || service.name === "workers") && service.env.SIXB_DRAIN_TIMEOUT_MS === undefined) {
572
- const drainTimeoutMs = retiringKillTimeoutMs(service.process.killTimeoutMs) - INTERRUPT_LEAD_MS;
573
- return {
574
- SIXB_DRAIN_TIMEOUT_MS: String(drainTimeoutMs),
575
- ...service.env
576
- };
577
- }
578
- return { ...service.env };
579
- }
580
- function renderCtl(layout) {
581
- return [
582
- "#!/bin/sh",
583
- `# ${GENERATED}`,
584
- `exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} "$@" --manifest ${shellQuote(layout.manifest)}`,
585
- ""
586
- ].join(`
587
- `);
588
- }
589
- function renderUnit(release, layout) {
590
- const stopSeconds = Math.ceil(Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000) + 10;
591
- return [
592
- `# ${GENERATED}`,
593
- "[Unit]",
594
- `Description=Sixb deployment ${release.name}`,
595
- "",
596
- "[Service]",
597
- "Type=simple",
598
- `WorkingDirectory=${systemdValue(layout.project)}`,
599
- `Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,
600
- `ExecStart=${systemdValue(layout.ctl)} supervise`,
601
- "Restart=always",
602
- "RestartSec=2",
603
- "KillSignal=SIGTERM",
604
- `TimeoutStopSec=${stopSeconds}`,
605
- "",
606
- "[Install]",
607
- "WantedBy=default.target",
608
- ""
609
- ].join(`
610
- `);
611
- }
612
- function renderCaddySnippet(release) {
613
- const sites = release.services.flatMap((service) => {
614
- if (!service.http)
615
- return [];
616
- const pages = service.name === "app";
617
- return [
618
- [
619
- `${service.http.domain} {`,
620
- ...service.name === "api" ? compressJson() : [],
621
- ` reverse_proxy ${service.http.host}:${service.http.port} {`,
622
- "\t\tlb_try_duration 5s",
623
- ...service.name === "api" ? keepWebSocketsThroughReload(service) : [],
624
- "\t}",
625
- ...pages ? updatePageOnProxyErrors() : [],
626
- "}"
627
- ].join(`
628
- `)
629
- ];
630
- });
631
- return [`# ${GENERATED}`, "", sites.join(`
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)}"
632
425
 
633
- `), ""].join(`
634
- `);
635
- }
636
- function keepWebSocketsThroughReload(service) {
637
- const seconds = retiringKillTimeoutMs(service.process.killTimeoutMs) / 1000;
638
- return [` stream_close_delay ${seconds}s`];
639
- }
640
- function compressJson() {
641
- return [
642
- "\tencode {",
643
- "\t\tzstd",
644
- "\t\tgzip",
645
- "\t\tmatch {",
646
- "\t\t\tstatus 200",
647
- "\t\t\theader Content-Type application/json*",
648
- "\t\t}",
649
- "\t}"
650
- ];
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
+ }
651
509
  }
652
- function updatePageOnProxyErrors() {
510
+ function releaseStepLabels(release) {
653
511
  return [
654
- "\thandle_errors 502 503 504 {",
655
- "\t\t@page {",
656
- "\t\t\tmethod GET",
657
- "\t\t\theader Accept *text/html*",
658
- "\t\t}",
659
- "\t\thandle @page {",
660
- '\t\t\theader Content-Type "text/html; charset=utf-8"',
661
- '\t\t\theader Cache-Control "no-store"',
662
- '\t\t\theader Retry-After "10"',
663
- "\t\t\trespond 503 {",
664
- "\t\t\t\tbody <<HTML",
665
- ...renderUpdatePage().split(`
666
- `).map((line) => ` ${line}`),
667
- "\t\t\t\tHTML",
668
- "\t\t\t}",
669
- "\t\t}",
670
- "\t\thandle {",
671
- '\t\t\trespond "Service temporarily unavailable" {err.status_code}',
672
- "\t\t}",
673
- "\t}"
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"
674
524
  ];
675
525
  }
676
- function systemdValue(value) {
677
- return value.replace(/%/g, "%%").replace(/\s/g, "\\x20");
678
- }
679
-
680
- // src/scripts.ts
681
- var STEP_MARKER = "__SIXB_STEP__";
682
- function renderPrepareScript(name, commit) {
683
- return [
684
- `root="$HOME"/${shellQuote(name)}`,
685
- 'mkdir -p "$root/deploy/incoming"',
686
- `incoming="$(mktemp -d "$root/deploy/incoming/${commit.slice(0, 12)}.XXXXXX")"`,
687
- 'chmod 755 "$incoming"',
688
- `printf '%s\\n%s\\n' "$HOME" "$incoming"`
689
- ].join(`
690
- `);
691
- }
692
- function renderReceiveScript(incoming, path) {
693
- const directory = path === "." ? incoming : `${incoming}/${path}`;
694
- return `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`;
695
- }
696
- function defaultSlotPorts(release) {
697
- const portOf = (name, fallback) => release.services.find((service) => service.name === name)?.http?.port ?? fallback;
698
- const blueApp = portOf("app", 3001);
699
- const blueApi = portOf("api", 3002);
700
- return {
701
- blue: { app: blueApp, api: blueApi },
702
- green: {
703
- app: blueApp + 10 <= 65535 ? blueApp + 10 : blueApp - 10,
704
- api: blueApi + 10 <= 65535 ? blueApi + 10 : blueApi - 10
705
- }
706
- };
526
+ function commandLabel(command) {
527
+ return [command.program, ...command.args].join(" ");
707
528
  }
708
529
  function deriveReleaseId(record) {
709
- const stamp = record.deployedAt.replace(/[-:.]/g, "").slice(0, 15);
530
+ const stamp = record.deployedAt.replace(/[-:.]/g, "").slice(0, 18);
710
531
  const sha = record.commit.slice(0, 12).replace(/[^a-zA-Z0-9_-]/g, "");
711
532
  return `${stamp}Z-${sha || "release"}`;
712
533
  }
713
- function renderDeployScript(input) {
714
- const { release, layout } = input;
715
- const releaseId = input.releaseId ?? deriveReleaseId(input.record);
716
- const targetRelease = releaseLayout(layout, releaseId);
717
- const slots = input.slotPorts ?? defaultSlotPorts(release);
718
- const blueRelease = releaseForSlot(release, slots.blue);
719
- const greenRelease = releaseForSlot(release, slots.green);
720
- const readinessUrl = (candidate) => {
721
- const api = candidate.services.find((service) => service.http?.readinessPath);
722
- return api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null;
723
- };
724
- const steps = [
725
- {
726
- label: "Prepare release",
727
- body: renderPrepareRelease(layout, targetRelease, input.incoming)
728
- },
729
- { label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },
730
- { label: "Install dependencies", body: renderInstallDependencies() },
731
- ...release.steps.env ? [envStep(release.steps.env, layout)] : [],
732
- ...release.steps.build.map((command, index, all) => index === all.length - 1 ? withCarriedAssets(runStep(command)) : runStep(command)),
733
- ...release.steps.beforeStart.flatMap((command) => isStorageMigration(command) ? [stopForSchemaChange(), runStep(command)] : [runStep(command)]),
734
- {
735
- label: "Start new release",
736
- body: renderStartCandidate({
737
- layout,
738
- targetRelease,
739
- blueRelease,
740
- greenRelease,
741
- slots
742
- })
743
- },
744
- {
745
- label: "Check services",
746
- body: renderCheckServices({
747
- blueReadyUrl: readinessUrl(blueRelease),
748
- greenReadyUrl: readinessUrl(greenRelease)
749
- })
750
- },
751
- {
752
- label: "Update routes",
753
- body: renderUpdateRoutes({
754
- layout,
755
- blueCaddy: renderCaddySnippet(blueRelease),
756
- greenCaddy: renderCaddySnippet(greenRelease)
757
- })
758
- },
759
- {
760
- label: "Activate release",
761
- body: renderActivateRelease({ release: blueRelease, layout, slots })
762
- }
763
- ];
764
- const script = [
765
- "set -euo pipefail",
766
- "main() {",
767
- renderEnvironment(release, layout, targetRelease),
768
- renderTakeLock(layout),
769
- renderUseRelease(layout, input.record),
770
- renderRestoreRoutes(),
771
- renderCandidateTrap(),
772
- ...steps.flatMap((step, index) => [
773
- `printf '\\n%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} start`,
774
- step.body,
775
- `printf '%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} done`
776
- ]),
777
- "}",
778
- "main </dev/null",
779
- ""
780
- ].join(`
781
- `);
782
- return { labels: steps.map((step) => step.label), script };
783
- }
784
- function renderEnvironment(release, layout, targetRelease) {
785
- const variables = {
786
- ROOT: layout.root,
787
- RELEASES_DIR: layout.releasesDir,
788
- CURRENT: layout.currentLink,
789
- CODE: layout.code,
790
- PROJECT: layout.project,
791
- SHARED_DIR: layout.sharedDir,
792
- SHARED_ENV: layout.sharedEnv,
793
- RELEASE_ID: targetRelease.id,
794
- RELEASE_ROOT: targetRelease.root,
795
- RELEASE_PROJECT: targetRelease.project,
796
- DEPLOY: layout.deployDir,
797
- MANIFEST: layout.manifest,
798
- CANDIDATE_MANIFEST: layout.candidateManifest,
799
- STATE_FILE: `${layout.runDir}/state.json`,
800
- BUN: layout.bun,
801
- BUN_DIR: layout.bunDir,
802
- BUN_VERSION: release.bunVersion,
803
- CTL: layout.ctl,
804
- UNIT: layout.unitName,
805
- UNIT_PATH: layout.unit,
806
- CADDY_DIR: layout.caddyDir,
807
- CADDY_SNIPPET: layout.caddySnippet,
808
- PREVIOUS_ROUTES: `${layout.deployDir}/Caddyfile.previous`
809
- };
810
- return [
811
- ...Object.entries(variables).map(([name, value]) => `${name}=${shellQuote(value)}`),
812
- ...Object.entries(release.env).map(([name, value]) => `export ${name}=${shellQuote(value)}`),
813
- 'export PATH="$BUN_DIR:$PATH"',
814
- 'printenv XDG_RUNTIME_DIR > /dev/null || export XDG_RUNTIME_DIR="/run/user/$(id -u)"',
815
- 'deploy_mode="none"',
816
- 'target_slot="blue"',
817
- 'prev_release=""'
818
- ].join(`
819
- `);
820
- }
821
- function renderTakeLock(layout) {
822
- return [
823
- `exec 9>${shellQuote(layout.lock)}`,
824
- "if ! flock -n 9; then",
825
- ' echo "Waiting for another deploy or script run of this project to finish\u2026"',
826
- "fi",
827
- "if ! flock -w 600 9; then",
828
- ' echo "Another deploy or script run of this project has held its lock for 10 minutes." >&2',
829
- " exit 1",
830
- "fi"
831
- ].join(`
832
- `);
833
- }
834
- function renderUseRelease(layout, record) {
835
- return [
836
- "use_release() {",
837
- ' ln -sfn "releases/$RELEASE_ID" "$CURRENT"',
838
- ' ln -sfn "current" "$CODE"',
839
- ` ${writeFileCommand(layout.releaseRecord, `${JSON.stringify(record)}
840
- `)}`,
841
- "}"
842
- ].join(`
843
- `);
844
- }
845
- function renderRestoreRoutes() {
846
- return [
847
- "restore_routes() {",
848
- ' if [ -f "$PREVIOUS_ROUTES" ]; then cp "$PREVIOUS_ROUTES" "$CADDY_SNIPPET"; else rm -f "$CADDY_SNIPPET"; fi',
849
- "}"
850
- ].join(`
851
- `);
852
- }
853
- function renderCandidateTrap() {
854
- return [
855
- "cleanup_candidate() {",
856
- " status=$?",
857
- ' if [ "$status" -eq 0 ]; then return; fi',
858
- "",
859
- ' case "$deploy_mode" in',
860
- " staged | routed)",
861
- ' if [ "$deploy_mode" = "routed" ]; then',
862
- " restore_routes || true",
863
- " if sudo -n /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
864
- " echo 'The routes are back on the live release.' >&2",
865
- " else",
866
- " echo 'Caddy did not reload the previous routes: run sudo systemctl reload caddy on the server.' >&2",
867
- " fi",
868
- " fi",
869
- ' "$BUN" "$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh" discard --manifest "$MANIFEST" > /dev/null 2>&1 || true',
870
- ' rm -f "$CANDIDATE_MANIFEST" "$DEPLOY/manifest.blue.json" "$DEPLOY/manifest.green.json"',
871
- " ;;",
872
- " stopped)",
873
- " echo 'The services were stopped for the storage migration and stay stopped. Fix what failed and deploy again.' >&2",
874
- " ;;",
875
- " activated | cold)",
876
- " echo 'The new release is in place, but it did not pass its checks.' >&2",
877
- " echo 'sixb deploy status and sixb deploy logs show what failed. To go back, deploy the previous commit with --ref.' >&2",
878
- " ;;",
879
- " esac",
880
- "}",
881
- "trap cleanup_candidate EXIT"
882
- ].join(`
883
- `);
884
- }
885
- function renderPrepareRelease(layout, targetRelease, incoming) {
886
- return [
887
- `incoming=${shellQuote(incoming)}`,
888
- `releases_dir=${shellQuote(layout.releasesDir)}`,
889
- `current=${shellQuote(layout.currentLink)}`,
890
- `code=${shellQuote(layout.code)}`,
891
- `project=${shellQuote(layout.project)}`,
892
- `shared_dir=${shellQuote(layout.sharedDir)}`,
893
- `shared_env=${shellQuote(layout.sharedEnv)}`,
894
- `release_root=${shellQuote(targetRelease.root)}`,
895
- `release_project=${shellQuote(targetRelease.project)}`,
896
- 'mkdir -p "$releases_dir" "$shared_dir"',
897
- 'if [ -d "$code" ] && [ ! -L "$code" ]; then',
898
- ' if [ -f "$project/.env" ] && [ ! -f "$shared_env" ]; then',
899
- ' cp -pf "$project/.env" "$shared_env" && chmod 600 "$shared_env"',
900
- " fi",
901
- ' rm -rf "$releases_dir/legacy"',
902
- ' mv "$code" "$releases_dir/legacy"',
903
- ' ln -sfn "releases/legacy" "$current"',
904
- ' ln -sfn "current" "$code"',
905
- "fi",
906
- 'if [ -f "$project/.env" ] && { [ ! -f "$shared_env" ] || [ "$project/.env" -nt "$shared_env" ]; }; then',
907
- ' cp -pf "$project/.env" "$shared_env" && chmod 600 "$shared_env"',
908
- "fi",
909
- 'if [ -L "$current" ]; then prev_release="$(basename "$(readlink "$current")")"; fi',
910
- 'rm -rf "$release_root"',
911
- 'mkdir -p "$release_root"',
912
- `(cd "$incoming" && tar -c -f - --exclude=.env .) | (cd "$release_root" && tar -x -f -)`,
913
- 'chmod 755 "$release_root"',
914
- 'mkdir -p "$release_project"',
915
- 'if [ -f "$shared_env" ]; then ln -sfn "$shared_env" "$release_project/.env"; fi',
916
- 'rm -rf "$incoming"',
917
- 'find "$(dirname "$incoming")" -mindepth 1 -maxdepth 1 -mmin +1440 -exec rm -rf {} + 2>/dev/null || true'
918
- ].join(`
919
- `);
920
- }
921
- function renderInstallBun(version) {
922
- const release = `https://github.com/oven-sh/bun/releases/download/bun-v${version}`;
923
- return [
924
- 'if [ ! -x "$BUN" ]; then',
925
- ' case "$(uname -m)" in',
926
- " x86_64 | amd64) arch=x64 ;;",
927
- " aarch64 | arm64) arch=aarch64 ;;",
928
- ' *) echo "Bun has no Linux build for $(uname -m)." >&2; exit 1 ;;',
929
- " esac",
930
- ' if [ "$arch" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi',
931
- ' asset="bun-linux-$arch"',
932
- ' download="$(mktemp -d)"',
933
- ` curl -fsSL --retry 3 -o "$download/$asset.zip" ${shellQuote(release)}"/$asset.zip"`,
934
- ` curl -fsSL --retry 3 -o "$download/SHASUMS256.txt" ${shellQuote(release)}/SHASUMS256.txt`,
935
- ' (cd "$download" && grep " $asset.zip\\$" SHASUMS256.txt | sha256sum -c --quiet -)',
936
- ' unzip -q "$download/$asset.zip" -d "$download"',
937
- ' mkdir -p "$BUN_DIR"',
938
- ' mv "$download/$asset/bun" "$BUN"',
939
- ' rm -rf "$download"',
940
- "fi",
941
- 'command -v node > /dev/null || ln -s "$BUN" "$BUN_DIR/node"',
942
- '"$BUN" --version'
943
- ].join(`
944
- `);
945
- }
946
- function renderInstallDependencies() {
947
- return [
948
- 'cd "$RELEASE_PROJECT"',
949
- '"$BUN" install --frozen-lockfile --backend=hardlink',
950
- "for bin in sixb sixb-deploy-ssh; do",
951
- ' if [ ! -e "$RELEASE_PROJECT/node_modules/.bin/$bin" ]; then',
952
- ' package="@sixb/cli"; [ "$bin" = sixb ] || package="@sixb/deploy-ssh"',
953
- ' echo "$package is not installed. Add it to the project dependencies." >&2',
954
- " exit 1",
955
- " fi",
956
- "done"
957
- ].join(`
958
- `);
959
- }
960
- function isStorageMigration(command) {
961
- return command.program === "sixb" && command.args[0] === "db" && command.args[1] === "migrate";
962
- }
963
- function stopForSchemaChange() {
964
- return {
965
- label: "Check storage migrations",
966
- body: [
967
- 'cd "$RELEASE_PROJECT"',
968
- "migrations=0",
969
- '"$BUN" "$RELEASE_PROJECT/node_modules/.bin/sixb" db migrate --check || migrations=$?',
970
- "",
971
- 'case "$migrations" in',
972
- " 0) ;;",
973
- " 2 | 3)",
974
- ' if [ "$migrations" = 3 ]; then',
975
- " echo 'This release changes the storage schema, so the services stop while it migrates.'",
976
- " else",
977
- " echo 'This release cannot tell whether its schema changes, so the services stop while it migrates.'",
978
- " fi",
979
- ' if systemctl --user is-active --quiet "$UNIT"; then systemctl --user stop "$UNIT"; fi',
980
- ' deploy_mode="stopped"',
981
- " ;;",
982
- ' *) exit "$migrations" ;;',
983
- "esac"
984
- ].join(`
985
- `)
986
- };
987
- }
988
- function runStep(command) {
989
- const program = command.program === "sixb" ? '"$RELEASE_PROJECT/node_modules/.bin/sixb"' : "";
990
- return {
991
- label: [command.program, ...command.args].join(" "),
992
- body: [
993
- 'cd "$RELEASE_PROJECT"',
994
- `"$BUN" ${program} ${command.args.map(shellQuote).join(" ")}`.replace(/ {2,}/g, " ")
995
- ].join(`
996
- `)
997
- };
998
- }
999
- function envStep(command, layout) {
1000
- const step = runStep(command);
1001
- return {
1002
- ...step,
1003
- body: [
1004
- `${step.body} --token-file ${shellQuote(layout.envToken)}`,
1005
- 'if [ -f "$RELEASE_PROJECT/.env" ] && [ ! -L "$RELEASE_PROJECT/.env" ]; then',
1006
- ' mv -f "$RELEASE_PROJECT/.env" "$SHARED_ENV" && chmod 600 "$SHARED_ENV"',
1007
- ' ln -sfn "$SHARED_ENV" "$RELEASE_PROJECT/.env"',
1008
- "fi"
1009
- ].join(`
1010
- `)
1011
- };
1012
- }
1013
- function withCarriedAssets(step) {
1014
- return {
1015
- ...step,
1016
- body: [
1017
- step.body,
1018
- 'new_app="$RELEASE_PROJECT/.sixb/dist/app"',
1019
- 'old_app="$PROJECT/.sixb/dist/app"',
1020
- 'own_list="$RELEASE_PROJECT/.sixb/dist/.own-assets"',
1021
- 'old_own="$PROJECT/.sixb/dist/.own-assets"',
1022
- 'if [ -d "$new_app" ]; then',
1023
- ' (cd "$new_app" && find . -type f | LC_ALL=C sort) > "$own_list"',
1024
- ' if [ -d "$old_app" ]; then',
1025
- ' source_list="$old_own"',
1026
- ' if [ ! -f "$source_list" ]; then',
1027
- ' source_list="$(mktemp)"',
1028
- ' (cd "$old_app" && find . -type f | LC_ALL=C sort) > "$source_list"',
1029
- ' temp_source_list="$source_list"',
1030
- " else",
1031
- ' temp_source_list=""',
1032
- " fi",
1033
- " while IFS= read -r rel; do",
1034
- ' base="$(basename "$rel")"',
1035
- ' case "$base" in',
1036
- " chunk-* | asset-* | app-*.* | shared-app-*.* | auth-*.*)",
1037
- ' if [ ! -e "$new_app/$rel" ] && [ -f "$old_app/$rel" ]; then',
1038
- ' mkdir -p "$(dirname "$new_app/$rel")"',
1039
- ' ln "$old_app/$rel" "$new_app/$rel" 2>/dev/null || cp -p "$old_app/$rel" "$new_app/$rel"',
1040
- " fi",
1041
- " ;;",
1042
- " esac",
1043
- ' done < "$source_list"',
1044
- ' if [ -n "$temp_source_list" ]; then rm -f "$temp_source_list"; fi',
1045
- " fi",
1046
- "fi"
1047
- ].join(`
1048
- `)
1049
- };
1050
- }
1051
- function renderStartCandidate(input) {
1052
- const { layout, targetRelease, blueRelease, greenRelease, slots } = input;
1053
- const blueManifest = renderProcessManifest(blueRelease, layout, {
1054
- projectDir: targetRelease.project,
1055
- slot: "blue"
1056
- });
1057
- const greenManifest = renderProcessManifest(greenRelease, layout, {
1058
- projectDir: targetRelease.project,
1059
- slot: "green"
1060
- });
1061
- const installServiceFiles = renderInstallServiceFiles(blueRelease, layout, slots);
1062
- return [
1063
- writeFileCommand(`${layout.deployDir}/manifest.blue.json`, `${JSON.stringify(blueManifest, null, 2)}
1064
- `),
1065
- writeFileCommand(`${layout.deployDir}/manifest.green.json`, `${JSON.stringify(greenManifest, null, 2)}
1066
- `),
1067
- "start_cold=1",
1068
- 'if [ -f "$MANIFEST" ] && systemctl --user is-active --quiet "$UNIT"; then start_cold=0; fi',
1069
- "",
1070
- `if [ "$start_cold" = 0 ] && ! grep -qs '"slot":' "$MANIFEST"; then`,
1071
- " echo 'The running supervisor predates blue-green deploys, so this deploy restarts it once.'",
1072
- " start_cold=1",
1073
- "fi",
1074
- "",
1075
- 'if [ "$start_cold" = 0 ]; then',
1076
- ` if grep -qs '"slot": "green"' "$MANIFEST"; then target_slot="blue"; else target_slot="green"; fi`,
1077
- ' cp "$DEPLOY/manifest.$target_slot.json" "$CANDIDATE_MANIFEST"',
1078
- ' "$BUN" "$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh" stage "$CANDIDATE_MANIFEST" --manifest "$MANIFEST"',
1079
- ' deploy_mode="staged"',
1080
- " started=$SECONDS",
1081
- "else",
1082
- ' target_slot="blue"',
1083
- " use_release",
1084
- ' deploy_mode="cold"',
1085
- ...installServiceFiles.map((line) => ` ${line}`),
1086
- ' mv "$DEPLOY/manifest.blue.json" "$MANIFEST"',
1087
- ' rm -f "$DEPLOY/manifest.green.json" "$CANDIDATE_MANIFEST"',
1088
- ' systemctl --user restart "$UNIT"',
1089
- ' systemctl --user is-active --quiet "$UNIT"',
1090
- " started=$SECONDS",
1091
- "fi"
1092
- ].join(`
1093
- `);
1094
- }
1095
- function renderCheckServices(input) {
1096
- const blueUrl = input.blueReadyUrl;
1097
- const greenUrl = input.greenReadyUrl ?? input.blueReadyUrl;
1098
- const waitForApi = blueUrl || greenUrl ? [
1099
- `ready_url=${shellQuote(blueUrl ?? "")}`,
1100
- 'if [ "$target_slot" = "green" ]; then',
1101
- ` ready_url=${shellQuote(greenUrl ?? "")}`,
1102
- "fi",
1103
- 'if [ -n "$ready_url" ]; then',
1104
- " ready=0",
1105
- " for attempt in $(seq 1 90); do",
1106
- ` if "$BUN" -e 'const r = await fetch(process.argv[1]).catch(() => null); process.exit(r?.ok ? 0 : 1)' "$ready_url" 2>/dev/null; then`,
1107
- " ready=1",
1108
- " break",
1109
- " fi",
1110
- " sleep 1",
1111
- " done",
1112
- ' if [ "$ready" != 1 ]; then',
1113
- ' echo "The API did not answer $ready_url within 90 seconds. Its latest log lines:" >&2',
1114
- ' "$CTL" logs api --tail 30 >&2 || true',
1115
- " exit 1",
1116
- " fi",
1117
- "fi"
1118
- ] : [];
1119
- return [
1120
- ...waitForApi,
1121
- "quiet=$((5 - (SECONDS - started)))",
1122
- 'if [ "$quiet" -gt 0 ]; then sleep "$quiet"; fi',
1123
- 'if [ "$deploy_mode" = "staged" ]; then',
1124
- ' "$BUN" "$RELEASE_PROJECT/node_modules/.bin/sixb-deploy-ssh" status --check --candidate --manifest "$MANIFEST"',
1125
- "else",
1126
- ' "$CTL" status --check',
1127
- "fi"
1128
- ].join(`
1129
- `);
1130
- }
1131
- function renderUpdateRoutes(input) {
1132
- const { layout, blueCaddy, greenCaddy } = input;
1133
- return [
1134
- writeFileCommand(`${layout.deployDir}/Caddyfile.blue`, blueCaddy),
1135
- writeFileCommand(`${layout.deployDir}/Caddyfile.green`, greenCaddy),
1136
- 'new="$DEPLOY/Caddyfile.$target_slot"',
1137
- 'cp "$new" "$DEPLOY/Caddyfile"',
1138
- 'rm -f "$DEPLOY/Caddyfile.blue" "$DEPLOY/Caddyfile.green"',
1139
- 'if cmp -s "$DEPLOY/Caddyfile" "$CADDY_SNIPPET"; then',
1140
- " echo 'Routes unchanged.'",
1141
- "else",
1142
- ' if [ ! -w "$CADDY_DIR" ]; then',
1143
- ' echo "$CADDY_DIR is missing or not writable, so this server is not set up for sixb deploy." >&2',
1144
- " exit 1",
1145
- " fi",
1146
- ' rm -f "$PREVIOUS_ROUTES"',
1147
- ' if [ -f "$CADDY_SNIPPET" ]; then cp "$CADDY_SNIPPET" "$PREVIOUS_ROUTES"; fi',
1148
- ' cp "$DEPLOY/Caddyfile" "$CADDY_SNIPPET"',
1149
- "",
1150
- ' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > "$DEPLOY/caddy-validate.log" 2>&1; then',
1151
- " restore_routes",
1152
- ' tail -n 20 "$DEPLOY/caddy-validate.log" >&2',
1153
- " echo 'Caddy rejected the routes; the previous ones are back in place.' >&2",
1154
- " exit 1",
1155
- " fi",
1156
- "",
1157
- " if ! sudo -n /usr/bin/systemctl reload caddy; then",
1158
- " restore_routes",
1159
- " echo 'Caddy did not reload; the previous routes are back in place.' >&2",
1160
- " exit 1",
1161
- " fi",
1162
- "",
1163
- ' if [ "$deploy_mode" = "staged" ]; then deploy_mode="routed"; fi',
1164
- "fi"
1165
- ].join(`
1166
- `);
1167
- }
1168
- function renderInstallServiceFiles(release, layout, slots) {
1169
- const reservedPorts = [
1170
- ...new Set(release.services.flatMap((service) => service.http && (service.name === "api" || service.name === "app") ? [slots.blue[service.name], slots.green[service.name]] : []))
1171
- ].map(String).join(`
1172
- `);
1173
- return [
1174
- writeFileCommand(`${layout.deployDir}/ports.txt`, reservedPorts ? `${reservedPorts}
1175
- ` : ""),
1176
- writeFileCommand(layout.ctl, renderCtl(layout)),
1177
- 'chmod 755 "$CTL"',
1178
- 'mkdir -p "$(dirname "$UNIT_PATH")"',
1179
- writeFileCommand(`${layout.unit}.new`, renderUnit(release, layout)),
1180
- 'if cmp -s "$UNIT_PATH.new" "$UNIT_PATH"; then',
1181
- ' rm -f "$UNIT_PATH.new"',
1182
- "else",
1183
- ' mv "$UNIT_PATH.new" "$UNIT_PATH"',
1184
- " systemctl --user daemon-reload",
1185
- ' systemctl --user enable "$UNIT"',
1186
- "fi"
1187
- ];
1188
- }
1189
- function renderActivateRelease(input) {
1190
- const hasExclusiveServices = input.release.services.some((service) => service.kind === "singleton" || service.kind === "script");
1191
- const installServiceFiles = renderInstallServiceFiles(input.release, input.layout, input.slots);
1192
- return [
1193
- 'if [ "$deploy_mode" = "staged" ] || [ "$deploy_mode" = "routed" ]; then',
1194
- ...installServiceFiles.map((line) => ` ${line}`),
1195
- " use_release",
1196
- ' deploy_mode="activated"',
1197
- ' mv "$CANDIDATE_MANIFEST" "$MANIFEST"',
1198
- ' rm -f "$DEPLOY/manifest.blue.json" "$DEPLOY/manifest.green.json"',
1199
- ' "$CTL" activate',
1200
- ...hasExclusiveServices ? [" sleep 2"] : [],
1201
- ' "$CTL" status --check',
1202
- "fi",
1203
- renderPruneReleases()
1204
- ].join(`
1205
- `);
1206
- }
1207
- function renderPruneReleases() {
1208
- return [
1209
- 'if [ -d "$RELEASES_DIR" ]; then',
1210
- ' for candidate_dir in "$RELEASES_DIR"/*; do',
1211
- ' [ -d "$candidate_dir" ] || continue',
1212
- ' name="$(basename "$candidate_dir")"',
1213
- ' if [ "$name" = "$RELEASE_ID" ] || [ "$name" = "$prev_release" ]; then continue; fi',
1214
- ' if [ -f "$STATE_FILE" ] && grep -qsF "$candidate_dir" "$STATE_FILE"; then continue; fi',
1215
- ' rm -rf "$candidate_dir"',
1216
- " done",
1217
- "fi"
1218
- ].join(`
1219
- `);
534
+
535
+ // src/server/logs.ts
536
+ var MAX_LOG_BYTES = 20 * 1024 * 1024;
537
+ var RECENT_BYTES = 256 * 1024;
538
+ var TERMINAL_CONTROL = /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[@-Z\\-_])/g;
539
+ function stripTerminalControl(line) {
540
+ return line.replace(TERMINAL_CONTROL, "");
1220
541
  }
1221
542
 
1222
543
  // src/transport.ts
1223
- import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
1224
- import { tmpdir as tmpdir2 } from "os";
1225
- import { join as join2 } from "path";
544
+ import { mkdtemp, rm } from "fs/promises";
545
+ import { tmpdir } from "os";
546
+ import { join } from "path";
1226
547
  class RemoteScriptError extends Error {
1227
548
  exitCode;
1228
549
  constructor(message, exitCode) {
@@ -1241,12 +562,12 @@ class SshShell {
1241
562
  this.controlDir = controlDir;
1242
563
  }
1243
564
  static async open(destination) {
1244
- const controlDir = await mkdtemp2(join2(tmpdir2(), "sixb-ssh-"));
565
+ const controlDir = await mkdtemp(join(tmpdir(), "sixb-ssh-"));
1245
566
  const shell = new SshShell(destination, controlDir);
1246
567
  try {
1247
568
  await runProcess(["ssh", ...shell.options(), "-M", "-N", "-f", destination], {});
1248
569
  } catch (error) {
1249
- await rm2(controlDir, { recursive: true, force: true });
570
+ await rm(controlDir, { recursive: true, force: true });
1250
571
  throw sshError(destination, error);
1251
572
  }
1252
573
  return shell;
@@ -1271,7 +592,7 @@ class SshShell {
1271
592
  }
1272
593
  async close() {
1273
594
  await runProcess(["ssh", ...this.options(), "-O", "exit", this.destination], {}).catch(() => {});
1274
- await rm2(this.controlDir, { recursive: true, force: true });
595
+ await rm(this.controlDir, { recursive: true, force: true });
1275
596
  }
1276
597
  options() {
1277
598
  return [
@@ -1288,7 +609,7 @@ class SshShell {
1288
609
  "-o",
1289
610
  "LogLevel=ERROR",
1290
611
  "-S",
1291
- join2(this.controlDir, "control")
612
+ join(this.controlDir, "control")
1292
613
  ];
1293
614
  }
1294
615
  }
@@ -1359,72 +680,125 @@ function sshError(destination, error) {
1359
680
  }
1360
681
  const output = error.message;
1361
682
  const host = destination.split("@").at(-1) ?? destination;
1362
- 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.`;
1363
- return new RemoteScriptError(`[SshTarget] ${reason}
683
+ return new RemoteScriptError(`[SshTarget] ${sshFailureReason(output, destination, host)}
1364
684
  ${output}`, error.exitCode);
1365
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
+ }
1366
709
 
1367
710
  // src/operations.ts
1368
711
  var NOT_DEPLOYED = "__SIXB_NOT_DEPLOYED__";
1369
- async function deployRelease(shell, user, release, source, context, slotPorts) {
1370
- const prepared = await capture(shell, renderPrepareScript(release.name, source.commit));
1371
- const [home, incoming] = prepared;
1372
- 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)
1373
732
  throw new Error("[SshTarget] The server did not report its home directory.");
1374
- }
1375
- const layout = deploymentLayout({
1376
- home,
1377
- user,
1378
- name: release.name,
1379
- projectPath: source.projectPath,
1380
- bunVersion: release.bunVersion
1381
- });
1382
- const { labels, script } = renderDeployScript({
1383
- release,
1384
- layout,
1385
- incoming,
1386
- ...slotPorts ? { slotPorts } : {},
1387
- record: {
1388
- commit: source.commit,
1389
- ref: source.ref,
1390
- deployedAt: new Date().toISOString(),
1391
- deployedBy: context.deployedBy
1392
- }
1393
- });
1394
- context.report({ type: "steps", labels: ["Upload source", ...labels] });
733
+ const labels = releaseStepLabels(release);
734
+ context.report({ type: "steps", labels });
1395
735
  context.report({ type: "step", index: 0, status: "running" });
1396
736
  for (const archive of source.archives) {
1397
- 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() });
1398
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);
1399
751
  context.report({ type: "step", index: 0, status: "done" });
1400
- 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 });
1401
763
  }
1402
- async function runReportingSteps(shell, script, context) {
1403
- const run = shell.run(script, {
1404
- onLine: (line) => {
1405
- const [marker, index, status] = line.split("\t");
1406
- if (marker === STEP_MARKER && (status === "start" || status === "done")) {
1407
- const step = Number(index) + 1;
1408
- context.report({
1409
- type: "step",
1410
- index: step,
1411
- status: status === "start" ? "running" : "done"
1412
- });
1413
- } else {
1414
- const output = stripTerminalControl(line);
1415
- if (output.trim())
1416
- context.report({ type: "output", line: output });
1417
- }
1418
- }
1419
- });
764
+ async function follow(shell, input) {
765
+ const { context, labels } = input;
766
+ let exit = null;
767
+ let failure = null;
1420
768
  try {
1421
- 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
+ });
1422
791
  } catch (error) {
1423
- if (error instanceof RemoteScriptError && error.exitCode !== 255) {
1424
- throw new Error(`[SshTarget] The step exited with code ${error.exitCode}.`);
1425
- }
1426
- 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 });
1427
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
+ });
1428
802
  }
1429
803
  async function readStatus(shell, name) {
1430
804
  const lines = await capture(shell, ctlScript(name, ["status", "--json"], { allowMissing: true }));
@@ -1506,160 +880,6 @@ async function capture(shell, script) {
1506
880
  return lines;
1507
881
  }
1508
882
 
1509
- // src/setup.ts
1510
- import { access } from "fs/promises";
1511
- var PACKAGED_CADDYFILE = "The Caddyfile is an easy way to configure your Caddy web server.";
1512
- function renderAdminScript(input) {
1513
- const user = shellQuote(input.user);
1514
- return [
1515
- "set -euo pipefail",
1516
- `deploy_user=${user}`,
1517
- `public_key=${shellQuote(input.publicKey)}`,
1518
- `admin_login=${shellQuote(input.admin)}`,
1519
- 'step() { printf "\\n== %s\\n" "$1"; }',
1520
- 'quiet() { log="$(mktemp)"; if "$@" > "$log" 2>&1; then rm -f "$log"; else status=$?; tail -n 20 "$log" >&2; rm -f "$log"; return "$status"; fi; }',
1521
- "",
1522
- 'step "Server"',
1523
- "if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then",
1524
- ' echo "sixb deploy needs an Ubuntu or Debian server with systemd." >&2',
1525
- " exit 1",
1526
- "fi",
1527
- '. /etc/os-release && echo "$PRETTY_NAME"',
1528
- "",
1529
- 'step "Packages"',
1530
- "export DEBIAN_FRONTEND=noninteractive",
1531
- 'missing=""',
1532
- "for package in git curl unzip ca-certificates gnupg; do",
1533
- ' dpkg -l "$package" 2> /dev/null | grep -q "^ii" || missing="$missing $package"',
1534
- "done",
1535
- 'if [ -n "$missing" ]; then',
1536
- ' echo "Installing$missing"',
1537
- " quiet apt-get update",
1538
- " quiet apt-get install -y $missing",
1539
- "fi",
1540
- "if ! command -v caddy > /dev/null; then",
1541
- ' echo "Installing caddy"',
1542
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |",
1543
- " gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
1544
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
1545
- " quiet apt-get update",
1546
- " quiet apt-get install -y caddy",
1547
- "fi",
1548
- `echo "git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)"`,
1549
- "",
1550
- 'step "Deploy user $deploy_user"',
1551
- 'id "$deploy_user" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group "$deploy_user"',
1552
- 'home="$(getent passwd "$deploy_user" | cut -d: -f6)"',
1553
- 'chmod 750 "$home"',
1554
- 'install -d -m 0700 -o "$deploy_user" -g "$deploy_user" "$home/.ssh"',
1555
- 'touch "$home/.ssh/authorized_keys"',
1556
- 'grep -qxF "$public_key" "$home/.ssh/authorized_keys" || echo "$public_key" >> "$home/.ssh/authorized_keys"',
1557
- 'chown "$deploy_user:$deploy_user" "$home/.ssh/authorized_keys"',
1558
- 'chmod 0600 "$home/.ssh/authorized_keys"',
1559
- 'loginctl enable-linger "$deploy_user"',
1560
- 'grep -qs XDG_RUNTIME_DIR "$home/.profile" ||',
1561
- ` echo 'export XDG_RUNTIME_DIR="/run/user/$(id -u)"' >> "$home/.profile"`,
1562
- 'chown "$deploy_user:$deploy_user" "$home/.profile"',
1563
- 'if [ "$admin_login" != root ]; then usermod -aG "$deploy_user" "$admin_login"; fi',
1564
- 'echo "$home, key-only, services start at boot"',
1565
- "",
1566
- 'step "Caddy reload"',
1567
- "groupadd -f sixb-deploy",
1568
- 'usermod -aG sixb-deploy "$deploy_user"',
1569
- 'sudoers="$(mktemp)"',
1570
- `echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > "$sudoers"`,
1571
- 'visudo -cf "$sudoers" > /dev/null',
1572
- 'install -m 0440 "$sudoers" /etc/sudoers.d/sixb',
1573
- 'rm -f "$sudoers"',
1574
- 'echo "$deploy_user may run sudo systemctl reload caddy, and nothing else"',
1575
- "",
1576
- 'step "Caddy routes"',
1577
- "caddyfile=/etc/caddy/Caddyfile",
1578
- "backup=/etc/caddy/Caddyfile.before-sixb-deploy",
1579
- "install -d -m 0755 /etc/caddy/sixb.d",
1580
- 'install -d -m 0755 -o "$deploy_user" -g "$deploy_user" "/etc/caddy/sixb.d/$deploy_user"',
1581
- `printf 'import /etc/caddy/sixb.d/%s/*.caddy\\n' "$deploy_user" > "/etc/caddy/sixb.d/$deploy_user.caddy"`,
1582
- "restart_caddy=0",
1583
- `if [ ! -s "$caddyfile" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} "$caddyfile"; then`,
1584
- ' if [ -f "$caddyfile" ]; then cp "$caddyfile" "$backup"; fi',
1585
- ` cat > "$caddyfile" <<'__SIXB_CADDYFILE__'`,
1586
- "# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.",
1587
- "{",
1588
- "\t# Only root and Caddy may change the running configuration.",
1589
- "\tadmin unix//var/lib/caddy/admin.sock",
1590
- "}",
1591
- "",
1592
- "import /etc/caddy/sixb.d/*.caddy",
1593
- "__SIXB_CADDYFILE__",
1594
- " restart_caddy=1",
1595
- `elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' "$caddyfile"; then`,
1596
- ' cp "$caddyfile" "$backup"',
1597
- ` printf '\\n# Routes written by sixb deploy, one folder per deploy user.\\nimport /etc/caddy/sixb.d/*.caddy\\n' >> "$caddyfile"`,
1598
- ` echo "Kept this server's Caddyfile and added one import; the previous one is $backup."`,
1599
- "fi",
1600
- 'if ! caddy validate --config "$caddyfile" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',
1601
- " tail -n 5 /tmp/sixb-caddy-validate.log >&2",
1602
- ' if [ -f "$backup" ]; then cp "$backup" "$caddyfile"; fi',
1603
- ' echo "Caddy rejected the configuration; the previous one is back in place." >&2',
1604
- " exit 1",
1605
- "fi",
1606
- 'if [ "$restart_caddy" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',
1607
- 'echo "/etc/caddy/sixb.d/$deploy_user"',
1608
- "",
1609
- 'step "Checks"',
1610
- "sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&",
1611
- ' echo "Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config." || true',
1612
- "sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&",
1613
- ' echo "Warning: root can log in with a password. Set PermitRootLogin prohibit-password." || true',
1614
- "if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then",
1615
- " for port in 80 443; do",
1616
- ' ufw status | grep -qE "^$port(/tcp)?\\s+ALLOW" ||',
1617
- ' echo "Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp"',
1618
- " done",
1619
- "fi",
1620
- 'echo "Done."'
1621
- ].join(`
1622
- `);
1623
- }
1624
- async function pickPublicKey(input) {
1625
- if (input.key) {
1626
- const path = input.key.endsWith(".pub") ? input.key : `${input.key}.pub`;
1627
- return { text: (await Bun.file(path).text()).trim(), source: path };
1628
- }
1629
- for (const identity of input.identityFiles) {
1630
- const path = `${identity}.pub`;
1631
- if (await access(path).then(() => true, () => false)) {
1632
- return { text: (await Bun.file(path).text()).trim(), source: path };
1633
- }
1634
- }
1635
- const agent = Bun.spawn(["ssh-add", "-L"], { stdout: "pipe", stderr: "ignore" });
1636
- const first = (await new Response(agent.stdout).text()).split(`
1637
- `).find((line) => line.trim());
1638
- if (await agent.exited === 0 && first)
1639
- return { text: first.trim(), source: "your SSH agent" };
1640
- throw new Error("[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`.");
1641
- }
1642
- async function ensureEnvToken(shell, name, createToken) {
1643
- const path = `"$HOME"/${shellQuote(`${name}/${ENV_TOKEN_FILE}`)}`;
1644
- const installed = await shell.run(`[ -s ${path} ]`).then(() => true, (error) => {
1645
- if (error instanceof RemoteScriptError && error.exitCode === 1)
1646
- return false;
1647
- throw error;
1648
- });
1649
- if (installed)
1650
- return false;
1651
- await shell.run([
1652
- "set -e",
1653
- "umask 077",
1654
- `mkdir -p "$HOME"/${shellQuote(name)}`,
1655
- `cat > ${path}.new`,
1656
- `mv ${path}.new ${path}`
1657
- ].join(`
1658
- `), { stdin: new Blob([`${await createToken()}
1659
- `]).stream() });
1660
- return true;
1661
- }
1662
-
1663
883
  // src/ssh-config.ts
1664
884
  import { homedir } from "os";
1665
885
  async function resolveSshConfig(destination) {
@@ -1689,55 +909,40 @@ async function resolveSshConfig(destination) {
1689
909
  }
1690
910
 
1691
911
  // src/ssh-target.ts
1692
- var OPTIONS = ["host", "user", "ports", "standbyPorts"];
1693
912
  var DEFAULT_USER = "sixb";
1694
- var DEFAULT_PORTS = {
1695
- app: 3001,
1696
- 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"
1697
916
  };
1698
- var LISTEN_HOST = "127.0.0.1";
1699
917
  var USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/;
918
+ var LISTEN_HOST = "127.0.0.1";
1700
919
 
1701
920
  class SshTarget {
1702
921
  kind = "ssh";
1703
922
  host;
1704
923
  user;
1705
924
  location;
1706
- #ports;
1707
- #standbyPorts;
1708
925
  constructor(options) {
1709
926
  if (typeof options !== "object" || options === null) {
1710
927
  throw new Error('[SshTarget] Pass options, such as `new SshTarget({ host: "203.0.113.10" })`.');
1711
928
  }
1712
929
  for (const key of Object.keys(options)) {
1713
- if (!OPTIONS.includes(key)) {
1714
- 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.`);
1715
935
  }
1716
936
  }
1717
937
  this.host = validateHost(options.host);
1718
938
  this.user = validateUser(options.user ?? DEFAULT_USER);
1719
939
  this.location = `${this.user}@${this.host}`;
1720
- const primary = { ...DEFAULT_PORTS, ...validatePorts(options.ports, "ports") };
1721
- const standbyDefaults = {
1722
- app: defaultStandbyPort(primary.app),
1723
- api: defaultStandbyPort(primary.api)
1724
- };
1725
- const standby = { ...standbyDefaults, ...validatePorts(options.standbyPorts, "standbyPorts") };
1726
- assertDistinctPorts(primary, standby);
1727
- this.#ports = primary;
1728
- this.#standbyPorts = standby;
1729
940
  }
1730
941
  listenAddress(service) {
1731
- return { host: LISTEN_HOST, port: this.#ports[service] };
1732
- }
1733
- standbyListenAddress(service) {
1734
- return { host: LISTEN_HOST, port: this.#standbyPorts[service] };
942
+ return { host: LISTEN_HOST, port: SLOT_PORTS.blue[service] };
1735
943
  }
1736
944
  deploy(release, source, context) {
1737
- return this.#connected((shell) => deployRelease(shell, this.user, release, source, context, {
1738
- blue: this.#ports,
1739
- green: this.#standbyPorts
1740
- }));
945
+ return this.#connected((shell) => deployRelease(shell, release, source, context));
1741
946
  }
1742
947
  status(context) {
1743
948
  return this.#connected((shell) => readStatus(shell, context.name));
@@ -1759,19 +964,12 @@ class SshTarget {
1759
964
  try {
1760
965
  server = await this.#connected(async (shell) => [
1761
966
  { id: "ssh", label: "SSH", status: "ok", detail: this.location },
1762
- ...await runChecks(shell, {
967
+ ...await checkHost(shell, {
1763
968
  name: context.name,
1764
969
  projectPath: context.projectPath,
1765
- ports: release.services.flatMap((service) => {
1766
- if (!service.http || service.name !== "api" && service.name !== "app")
1767
- return [];
1768
- return [
1769
- { service: service.name, port: this.#ports[service.name] },
1770
- { service: `${service.name}-standby`, port: this.#standbyPorts[service.name] }
1771
- ];
1772
- }),
1773
- envFromSource: release.steps.env !== undefined,
1774
- 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
1775
973
  })
1776
974
  ]);
1777
975
  } catch (error) {
@@ -1779,72 +977,6 @@ class SshTarget {
1779
977
  }
1780
978
  return [...server, ...await dns];
1781
979
  }
1782
- async setup(release, context) {
1783
- const before = await this.check(release, context);
1784
- const serverFixes = before.filter((check) => check.status === "fixable" && check.id !== "project.env" && check.id !== ENV_TOKEN_CHECK || check.id === "ssh" && check.status !== "ok");
1785
- const unreachable = before.find((check) => check.id === "ssh" && check.status === "manual");
1786
- if (unreachable) {
1787
- throw new Error(`[SshTarget] ${unreachable.detail}`);
1788
- }
1789
- if (serverFixes.length > 0) {
1790
- const admin = context.admin ?? "root";
1791
- const { identityFiles } = await resolveSshConfig(this.location);
1792
- const key = await pickPublicKey({ key: context.key, identityFiles });
1793
- context.write(`Setting up ${this.host} as ${admin}, authorizing ${key.source} for ${this.user}.`);
1794
- await runAsAdmin(`${admin}@${this.host}`, admin === "root", renderAdminScript({ user: this.user, publicKey: key.text, admin }));
1795
- }
1796
- context.write(`Preparing ${context.name} as ${this.user}.`);
1797
- await this.#connected((shell) => shell.run([
1798
- `root="$HOME"/${shellQuote(context.name)}`,
1799
- `project="$HOME"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,
1800
- 'mkdir -p "$root/shared"',
1801
- 'if [ ! -L "$root/code" ]; then mkdir -p "$project"; fi',
1802
- 'if [ -f "$root/shared/.env" ]; then chmod 600 "$root/shared/.env"; fi',
1803
- 'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi',
1804
- `token="$HOME"/${shellQuote(`${context.name}/${ENV_TOKEN_FILE}`)}`,
1805
- 'if [ -f "$token" ]; then chmod 600 "$token"; fi'
1806
- ].join(`
1807
- `)));
1808
- const { createEnvToken } = context;
1809
- if (release.steps.env && createEnvToken) {
1810
- const installed = await this.#connected((shell) => ensureEnvToken(shell, context.name, createEnvToken));
1811
- if (installed)
1812
- context.write(`Installed a read-only token for ${context.name}.`);
1813
- }
1814
- }
1815
- access = {
1816
- list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),
1817
- add: (key) => this.#connected((shell) => addKey(shell, key)).then(withoutLine),
1818
- remove: (match) => this.#connected(async (shell) => (await removeKeys(shell, match)).map(withoutLine))
1819
- };
1820
- ci = {
1821
- create: (job, context) => this.#createCiKey(job, context.name)
1822
- };
1823
- async#createCiKey(job, name) {
1824
- const ssh = await resolveSshConfig(this.location);
1825
- if (ssh.proxyJump) {
1826
- 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.");
1827
- }
1828
- const comment = `sixb-ci:${name}@${job}`;
1829
- const pair = await generateCiKey(comment);
1830
- const { key, hostKeys } = await this.#connected(async (shell) => ({
1831
- hostKeys: await readHostKeys(shell),
1832
- key: await addKey(shell, pair.publicKey, "restrict")
1833
- }));
1834
- return {
1835
- description: `${key.fingerprint} for ${this.location}, restricted to running commands`,
1836
- secrets: {
1837
- SIXB_DEPLOY_SSH_KEY: pair.privateKey,
1838
- SIXB_DEPLOY_KNOWN_HOSTS: knownHostsLines(hostKeys, ssh.hostname, ssh.port).join(`
1839
- `)
1840
- },
1841
- install: renderCiInstall({ host: this.host, hostname: ssh.hostname, port: ssh.port }),
1842
- retireOthers: () => this.#connected(async (shell) => (await removeKeysWhere(shell, (other) => other.comment === comment && other.fingerprint !== key.fingerprint)).map(withoutLine)),
1843
- revoke: () => this.#connected(async (shell) => {
1844
- await removeKeysWhere(shell, (other) => other.fingerprint === key.fingerprint);
1845
- })
1846
- };
1847
- }
1848
980
  async#connected(work) {
1849
981
  const shell = await SshShell.open(this.location);
1850
982
  try {
@@ -1854,24 +986,14 @@ class SshTarget {
1854
986
  }
1855
987
  }
1856
988
  }
1857
- function defaultStandbyPort(port) {
1858
- return port + 10 <= 65535 ? port + 10 : port - 10;
1859
- }
1860
- function assertDistinctPorts(primary, standby) {
1861
- const entries = [
1862
- ["ports.app", primary.app],
1863
- ["ports.api", primary.api],
1864
- ["standbyPorts.app", standby.app],
1865
- ["standbyPorts.api", standby.api]
1866
- ];
1867
- const seen = new Map;
1868
- for (const [label, port] of entries) {
1869
- const previous = seen.get(port);
1870
- if (previous) {
1871
- throw new Error(`[SshTarget] ${label} (${port}) conflicts with ${previous}. Give each HTTP service and slot its own port.`);
1872
- }
1873
- seen.set(port, label);
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.");
1874
995
  }
996
+ return value;
1875
997
  }
1876
998
  function validateHost(value) {
1877
999
  if (typeof value !== "string" || value.trim() === "") {
@@ -1879,7 +1001,7 @@ function validateHost(value) {
1879
1001
  }
1880
1002
  const host = value.trim();
1881
1003
  if (host.includes("@")) {
1882
- 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\`.`);
1883
1005
  }
1884
1006
  if (host.startsWith("-") || /[\s/\\]/.test(host)) {
1885
1007
  throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`);
@@ -1889,68 +1011,18 @@ function validateHost(value) {
1889
1011
  }
1890
1012
  return host;
1891
1013
  }
1892
- function validateUser(value) {
1893
- if (value === "root") {
1894
- throw new Error("[SshTarget] Deployments never run as root. Use a deploy user without sudo, such as the " + 'default "sixb".');
1895
- }
1896
- if (typeof value !== "string" || !USER_PATTERN.test(value)) {
1897
- 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.");
1898
- }
1899
- return value;
1900
- }
1901
- function validatePorts(value, field) {
1902
- if (value === undefined)
1903
- return {};
1904
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1905
- throw new Error(`[SshTarget] ${field} must be an object, such as \`{ api: 3012 }\`.`);
1906
- }
1907
- const ports = {};
1908
- for (const [service, port] of Object.entries(value)) {
1909
- if (!Object.hasOwn(DEFAULT_PORTS, service)) {
1910
- throw new Error(`[SshTarget] ${field}.${service} is not an HTTP service. Available: api, app.`);
1911
- }
1912
- if (!Number.isInteger(port) || port < 1024 || port > 65535) {
1913
- throw new Error(`[SshTarget] ${field}.${service} must be a port from 1024 to 65535.`);
1914
- }
1915
- ports[service] = port;
1916
- }
1917
- return ports;
1918
- }
1919
1014
  function sshCheck(location, error) {
1920
- const message = (error instanceof Error ? error.message : String(error)).split(`
1921
- `)[0]?.replace(/^\[SshTarget\] /, "") ?? "";
1922
- if (error instanceof RemoteScriptError && /refused your SSH key/.test(message)) {
1923
- return {
1924
- id: "ssh",
1925
- label: "SSH",
1926
- status: "fixable",
1927
- detail: message,
1928
- 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.`
1929
- };
1930
- }
1015
+ const [message = ""] = (error instanceof Error ? error.message : String(error)).split(`
1016
+ `);
1931
1017
  return {
1932
1018
  id: "ssh",
1933
1019
  label: "SSH",
1934
- status: "manual",
1935
- detail: message || `Cannot reach ${location}.`
1020
+ status: "fail",
1021
+ detail: message.replace(/^\[SshTarget\] /, "") || `Cannot reach ${location}.`
1936
1022
  };
1937
1023
  }
1938
- function withoutLine({ type, fingerprint, comment, restricted }) {
1939
- return { type, fingerprint, comment, restricted };
1940
- }
1941
- async function runAsAdmin(destination, root, script) {
1942
- const command = `${root ? "" : "sudo "}bash -c ${shellQuote(script)}`;
1943
- const ssh = ["ssh", "-tt", "-o", "ConnectTimeout=15", "-o", "LogLevel=ERROR"];
1944
- const child = Bun.spawn([...ssh, destination, command], {
1945
- stdio: ["inherit", "inherit", "inherit"]
1946
- });
1947
- const exitCode = await child.exited;
1948
- if (exitCode !== 0) {
1949
- throw new Error(`[SshTarget] Setting up the server as ${destination} failed (exit code ${exitCode}).`);
1950
- }
1951
- }
1952
1024
  export {
1953
1025
  SshTarget
1954
1026
  };
1955
1027
 
1956
- //# debugId=F0A8F6E476574A6F64756E2164756E21
1028
+ //# debugId=EFD7A0BD5214D5D664756E2164756E21