@sixb/deploy-ssh 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +74 -0
- package/dist/access.d.ts +11 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/check.d.ts +28 -0
- package/dist/check.d.ts.map +1 -0
- package/dist/ci.d.ts +27 -0
- package/dist/ci.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1415 -0
- package/dist/index.js.map +24 -0
- package/dist/keys.d.ts +13 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/layout.d.ts +38 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/operations.d.ts +10 -0
- package/dist/operations.d.ts.map +1 -0
- package/dist/render.d.ts +15 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/scripts.d.ts +37 -0
- package/dist/scripts.d.ts.map +1 -0
- package/dist/server/cli.d.ts +3 -0
- package/dist/server/cli.d.ts.map +1 -0
- package/dist/server/logs.d.ts +25 -0
- package/dist/server/logs.d.ts.map +1 -0
- package/dist/server/manifest.d.ts +30 -0
- package/dist/server/manifest.d.ts.map +1 -0
- package/dist/server/state.d.ts +32 -0
- package/dist/server/state.d.ts.map +1 -0
- package/dist/server/supervisor.d.ts +16 -0
- package/dist/server/supervisor.d.ts.map +1 -0
- package/dist/setup.d.ts +25 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/shell.d.ts +5 -0
- package/dist/shell.d.ts.map +1 -0
- package/dist/ssh-config.d.ts +12 -0
- package/dist/ssh-config.d.ts.map +1 -0
- package/dist/ssh-target.d.ts +39 -0
- package/dist/ssh-target.d.ts.map +1 -0
- package/dist/transport.d.ts +45 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/dist/update-page.d.ts +6 -0
- package/dist/update-page.d.ts.map +1 -0
- package/package.json +61 -0
- package/src/access.ts +107 -0
- package/src/check.ts +215 -0
- package/src/ci.ts +88 -0
- package/src/index.ts +2 -0
- package/src/keys.ts +57 -0
- package/src/layout.ts +69 -0
- package/src/operations.ts +158 -0
- package/src/render.ts +129 -0
- package/src/scripts.ts +305 -0
- package/src/server/cli.ts +157 -0
- package/src/server/logs.ts +180 -0
- package/src/server/manifest.ts +112 -0
- package/src/server/state.ts +81 -0
- package/src/server/supervisor.ts +542 -0
- package/src/setup.ts +166 -0
- package/src/shell.ts +10 -0
- package/src/ssh-config.ts +35 -0
- package/src/ssh-target.ts +347 -0
- package/src/transport.ts +211 -0
- package/src/update-page.ts +44 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1415 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/ssh-target.ts
|
|
3
|
+
import { isIPv6 } from "net";
|
|
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
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/shell.ts
|
|
52
|
+
function shellQuote(value) {
|
|
53
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
54
|
+
}
|
|
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
|
+
|
|
60
|
+
// src/access.ts
|
|
61
|
+
async function listKeys(shell) {
|
|
62
|
+
return [...(await readKeysFile(shell)).keys];
|
|
63
|
+
}
|
|
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;
|
|
72
|
+
}
|
|
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;
|
|
79
|
+
}
|
|
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;
|
|
91
|
+
}
|
|
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
|
+
}
|
|
99
|
+
});
|
|
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
|
+
}
|
|
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
|
+
`));
|
|
127
|
+
}
|
|
128
|
+
function sha256(content) {
|
|
129
|
+
return createHash2("sha256").update(content).digest("hex");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/check.ts
|
|
133
|
+
import { resolve4, resolve6 } from "dns/promises";
|
|
134
|
+
import { isIP } from "net";
|
|
135
|
+
import { posix } from "path";
|
|
136
|
+
var CHECK_MARKER = "__SIXB_CHECK__";
|
|
137
|
+
var TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"];
|
|
138
|
+
function renderCheckScript(input) {
|
|
139
|
+
const project = posix.join(input.name, "code", input.projectPath);
|
|
140
|
+
return [
|
|
141
|
+
`emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
|
|
142
|
+
`project="$HOME"/${shellQuote(project)}`,
|
|
143
|
+
`manifest="$HOME"/${shellQuote(input.name)}/deploy/processes.json`,
|
|
144
|
+
'routes_dir="/etc/caddy/sixb.d/$USER"',
|
|
145
|
+
`snippet="$routes_dir"/${shellQuote(`${input.name}.caddy`)}`,
|
|
146
|
+
"",
|
|
147
|
+
"if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then",
|
|
148
|
+
' emit server.os ok "$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',
|
|
149
|
+
"else",
|
|
150
|
+
' emit server.os manual "$(uname -s) without apt and systemd"',
|
|
151
|
+
"fi",
|
|
152
|
+
"",
|
|
153
|
+
'missing=""',
|
|
154
|
+
`for tool in ${TOOLS.join(" ")}; do command -v "$tool" > /dev/null || missing="$missing $tool"; done`,
|
|
155
|
+
'if [ -n "$missing" ]; then emit server.tools fixable "missing:$missing"',
|
|
156
|
+
'else emit server.tools ok "Caddy $(caddy version 2>/dev/null | cut -d" " -f1), git, curl, unzip"; fi',
|
|
157
|
+
"",
|
|
158
|
+
'if [ -e "/var/lib/systemd/linger/$USER" ]; then emit server.linger ok "on for $USER"',
|
|
159
|
+
'else emit server.linger fixable "off for $USER: services would stop when you log out"; fi',
|
|
160
|
+
"",
|
|
161
|
+
"if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
|
|
162
|
+
' emit server.reload ok "$USER may reload Caddy"',
|
|
163
|
+
"else",
|
|
164
|
+
' emit server.reload fixable "$USER may not run sudo systemctl reload caddy"',
|
|
165
|
+
"fi",
|
|
166
|
+
"",
|
|
167
|
+
'problems=""',
|
|
168
|
+
'[ -d "$routes_dir" ] && [ -w "$routes_dir" ] || problems="$problems; $routes_dir is missing or not writable"',
|
|
169
|
+
'grep -qsF "import $routes_dir/*.caddy" "/etc/caddy/sixb.d/$USER.caddy" || problems="$problems; /etc/caddy/sixb.d/$USER.caddy does not import it"',
|
|
170
|
+
`grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems="$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy"`,
|
|
171
|
+
'if [ -z "$problems" ]; then emit server.routes ok "$routes_dir"',
|
|
172
|
+
`else emit server.routes fixable "$(printf '%s' "$problems" | sed 's/^; //')"; fi`,
|
|
173
|
+
"",
|
|
174
|
+
"if ss -ltnH 2> /dev/null | grep -qE '(127\\.0\\.0\\.1|\\[::1\\]):2019 '; then",
|
|
175
|
+
` emit server.admin-api warning "Caddy's admin API listens on localhost:2019, where any process on the server can change every route"`,
|
|
176
|
+
"else",
|
|
177
|
+
' emit server.admin-api ok "not on localhost:2019"',
|
|
178
|
+
"fi",
|
|
179
|
+
"",
|
|
180
|
+
'if [ ! -f "$project/.env" ]; then emit project.env manual "$project/.env does not exist"',
|
|
181
|
+
'elif [ "$(stat -c %a "$project/.env")" != 600 ]; then emit project.env fixable "$project/.env is readable by others (mode $(stat -c %a "$project/.env"))"',
|
|
182
|
+
'else emit project.env ok "$project/.env"; fi',
|
|
183
|
+
"",
|
|
184
|
+
...input.ports.flatMap(({ service, port }) => [
|
|
185
|
+
`if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
|
|
186
|
+
` if grep -qs '"--port",' "$manifest" && grep -A1 -s '"--port",' "$manifest" | grep -q '"${port}"'; then`,
|
|
187
|
+
` emit project.port.${service} ok "${port}, used by this deployment"`,
|
|
188
|
+
" else",
|
|
189
|
+
` emit project.port.${service} manual "${port} is in use by another program"`,
|
|
190
|
+
" fi",
|
|
191
|
+
`elif grep -ls '127.0.0.1:${port}\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv "^$snippet$"; then`,
|
|
192
|
+
` emit project.port.${service} manual "${port} is routed to another deployment"`,
|
|
193
|
+
"else",
|
|
194
|
+
` emit project.port.${service} ok "${port}"`,
|
|
195
|
+
"fi"
|
|
196
|
+
]),
|
|
197
|
+
"",
|
|
198
|
+
`free_kb="$(df -Pk "$HOME" | awk 'NR == 2 { print $4 + 0 }')"`,
|
|
199
|
+
'if [ "$free_kb" -lt 2097152 ]; then emit server.disk warning "$((free_kb / 1024)) MB free"',
|
|
200
|
+
'else emit server.disk ok "$((free_kb / 1048576)) GB free"; fi'
|
|
201
|
+
].join(`
|
|
202
|
+
`);
|
|
203
|
+
}
|
|
204
|
+
function parseCheckOutput(lines, context) {
|
|
205
|
+
return lines.flatMap((line) => {
|
|
206
|
+
const [marker, id, status, detail] = line.split("\t");
|
|
207
|
+
if (marker !== CHECK_MARKER || !id || !isStatus(status))
|
|
208
|
+
return [];
|
|
209
|
+
return [describe(id, status, detail ?? "", context)];
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
async function checkDns(release, hostname) {
|
|
213
|
+
const expected = isIP(hostname) ? [hostname] : await lookup(hostname);
|
|
214
|
+
return Promise.all(release.services.flatMap((service) => {
|
|
215
|
+
const http = service.http;
|
|
216
|
+
if (!http)
|
|
217
|
+
return [];
|
|
218
|
+
return [
|
|
219
|
+
(async () => {
|
|
220
|
+
const found = await lookup(http.domain);
|
|
221
|
+
const id = `dns.${service.name}`;
|
|
222
|
+
const label = `${service.name} DNS`;
|
|
223
|
+
if (expected.length > 0 && found.some((address) => expected.includes(address))) {
|
|
224
|
+
return { id, label, status: "ok", detail: `${http.domain} \u2192 ${found.join(", ")}` };
|
|
225
|
+
}
|
|
226
|
+
const target = expected[0] ?? hostname;
|
|
227
|
+
return {
|
|
228
|
+
id,
|
|
229
|
+
label,
|
|
230
|
+
status: "warning",
|
|
231
|
+
detail: found.length > 0 ? `${http.domain} \u2192 ${found.join(", ")}` : `${http.domain} does not resolve`,
|
|
232
|
+
remedy: `Point ${http.domain} at ${target} with an ${isIP(target) === 6 ? "AAAA" : "A"} record. Until then, Caddy cannot get it a certificate.`
|
|
233
|
+
};
|
|
234
|
+
})()
|
|
235
|
+
];
|
|
236
|
+
}));
|
|
237
|
+
}
|
|
238
|
+
async function runChecks(shell, input) {
|
|
239
|
+
const lines = [];
|
|
240
|
+
await shell.run(renderCheckScript(input), {
|
|
241
|
+
onLine: (line, stream) => {
|
|
242
|
+
if (stream === "stdout")
|
|
243
|
+
lines.push(line);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
return parseCheckOutput(lines, input);
|
|
247
|
+
}
|
|
248
|
+
var LABELS = {
|
|
249
|
+
"server.os": "Server",
|
|
250
|
+
"server.tools": "Server tools",
|
|
251
|
+
"server.linger": "Services at boot",
|
|
252
|
+
"server.reload": "Caddy reload",
|
|
253
|
+
"server.routes": "Caddy routes",
|
|
254
|
+
"server.admin-api": "Caddy admin API",
|
|
255
|
+
"server.disk": "Disk space",
|
|
256
|
+
"project.env": ".env"
|
|
257
|
+
};
|
|
258
|
+
function describe(id, status, detail, context) {
|
|
259
|
+
const label = LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13)} port` : id);
|
|
260
|
+
const check = { id, label, status, detail };
|
|
261
|
+
if (status === "ok")
|
|
262
|
+
return check;
|
|
263
|
+
if (status === "fixable")
|
|
264
|
+
return { ...check, remedy: "Run `sixb deploy setup`." };
|
|
265
|
+
if (id === "server.os")
|
|
266
|
+
return { ...check, remedy: "Deploy to an Ubuntu or Debian server." };
|
|
267
|
+
if (id === "project.env") {
|
|
268
|
+
const path = detail.replace(/ does not exist$/, "");
|
|
269
|
+
return {
|
|
270
|
+
...check,
|
|
271
|
+
remedy: `Create it with the project's settings: \`ssh ${context.location} 'install -m 600 /dev/null ${path}'\`, then edit it.`
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
if (id.startsWith("project.port.")) {
|
|
275
|
+
return { ...check, remedy: "Give this service another port in the target's `ports`." };
|
|
276
|
+
}
|
|
277
|
+
if (id === "server.admin-api") {
|
|
278
|
+
return {
|
|
279
|
+
...check,
|
|
280
|
+
remedy: "Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile."
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
return check;
|
|
284
|
+
}
|
|
285
|
+
function isStatus(value) {
|
|
286
|
+
return value === "ok" || value === "fixable" || value === "manual" || value === "warning";
|
|
287
|
+
}
|
|
288
|
+
async function lookup(hostname) {
|
|
289
|
+
const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))]);
|
|
290
|
+
return [...v4, ...v6];
|
|
291
|
+
}
|
|
292
|
+
async function settle(query) {
|
|
293
|
+
let timer;
|
|
294
|
+
try {
|
|
295
|
+
return await Promise.race([
|
|
296
|
+
query.catch(() => []),
|
|
297
|
+
new Promise((resolveTimeout) => {
|
|
298
|
+
timer = setTimeout(() => resolveTimeout([]), 4000);
|
|
299
|
+
})
|
|
300
|
+
]);
|
|
301
|
+
} finally {
|
|
302
|
+
clearTimeout(timer);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/ci.ts
|
|
307
|
+
import { mkdtemp, readFile, rm } from "fs/promises";
|
|
308
|
+
import { tmpdir } from "os";
|
|
309
|
+
import { join } from "path";
|
|
310
|
+
async function generateCiKey(comment) {
|
|
311
|
+
const dir = await mkdtemp(join(tmpdir(), "sixb-ci-key-"));
|
|
312
|
+
try {
|
|
313
|
+
const path = join(dir, "key");
|
|
314
|
+
const child = Bun.spawn(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", path], {
|
|
315
|
+
stdin: "ignore",
|
|
316
|
+
stdout: "ignore",
|
|
317
|
+
stderr: "pipe"
|
|
318
|
+
});
|
|
319
|
+
if (await child.exited !== 0) {
|
|
320
|
+
const reason = (await new Response(child.stderr).text()).trim();
|
|
321
|
+
throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`);
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
privateKey: await readFile(path, "utf8"),
|
|
325
|
+
publicKey: (await readFile(`${path}.pub`, "utf8")).trim()
|
|
326
|
+
};
|
|
327
|
+
} finally {
|
|
328
|
+
await rm(dir, { recursive: true, force: true });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async function readHostKeys(shell) {
|
|
332
|
+
const keys = [];
|
|
333
|
+
await shell.run("cat /etc/ssh/ssh_host_*_key.pub", {
|
|
334
|
+
onLine: (line, stream) => {
|
|
335
|
+
const [type, key] = line.trim().split(/\s+/);
|
|
336
|
+
if (stream === "stdout" && type && key)
|
|
337
|
+
keys.push(`${type} ${key}`);
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
if (keys.length === 0)
|
|
341
|
+
throw new Error("[SshTarget] Could not read the server's SSH host keys.");
|
|
342
|
+
return keys;
|
|
343
|
+
}
|
|
344
|
+
function knownHostsLines(hostKeys, hostname, port) {
|
|
345
|
+
const name = port === 22 ? hostname : `[${hostname}]:${port}`;
|
|
346
|
+
return hostKeys.map((key) => `${name} ${key}`);
|
|
347
|
+
}
|
|
348
|
+
function renderCiInstall(input) {
|
|
349
|
+
return [
|
|
350
|
+
"install -d -m 700 ~/.ssh",
|
|
351
|
+
"install -m 600 /dev/null ~/.ssh/sixb_deploy",
|
|
352
|
+
`printf '%s\\n' "$SIXB_DEPLOY_SSH_KEY" > ~/.ssh/sixb_deploy`,
|
|
353
|
+
`printf '%s\\n' "$SIXB_DEPLOY_KNOWN_HOSTS" > ~/.ssh/sixb_known_hosts`,
|
|
354
|
+
"cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'",
|
|
355
|
+
`Host ${input.host}`,
|
|
356
|
+
` HostName ${input.hostname}`,
|
|
357
|
+
` Port ${input.port}`,
|
|
358
|
+
" IdentityFile ~/.ssh/sixb_deploy",
|
|
359
|
+
" IdentitiesOnly yes",
|
|
360
|
+
" UserKnownHostsFile ~/.ssh/sixb_known_hosts",
|
|
361
|
+
" StrictHostKeyChecking yes",
|
|
362
|
+
"__SIXB_SSH_CONFIG__"
|
|
363
|
+
];
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// src/layout.ts
|
|
367
|
+
import { posix as posix2 } from "path";
|
|
368
|
+
function deploymentLayout(input) {
|
|
369
|
+
const root = posix2.join(input.home, input.name);
|
|
370
|
+
const code = posix2.join(root, "code");
|
|
371
|
+
const deployDir = posix2.join(root, "deploy");
|
|
372
|
+
const runDir = posix2.join(root, "run");
|
|
373
|
+
const bunDir = posix2.join(input.home, ".sixb", "bun", input.bunVersion);
|
|
374
|
+
const unitName = `sixb-${input.name}.service`;
|
|
375
|
+
const caddyDir = posix2.join("/etc/caddy/sixb.d", input.user);
|
|
376
|
+
return {
|
|
377
|
+
root,
|
|
378
|
+
code,
|
|
379
|
+
project: posix2.join(code, input.projectPath),
|
|
380
|
+
deployDir,
|
|
381
|
+
incomingDir: posix2.join(deployDir, "incoming"),
|
|
382
|
+
lock: posix2.join(deployDir, "lock"),
|
|
383
|
+
fileList: posix2.join(deployDir, "files.txt"),
|
|
384
|
+
manifest: posix2.join(deployDir, "processes.json"),
|
|
385
|
+
releaseRecord: posix2.join(deployDir, "release.json"),
|
|
386
|
+
ctl: posix2.join(deployDir, "ctl"),
|
|
387
|
+
runDir,
|
|
388
|
+
logDir: posix2.join(runDir, "logs"),
|
|
389
|
+
bunDir,
|
|
390
|
+
bun: posix2.join(bunDir, "bun"),
|
|
391
|
+
unitName,
|
|
392
|
+
unit: posix2.join(input.home, ".config", "systemd", "user", unitName),
|
|
393
|
+
caddyDir,
|
|
394
|
+
caddySnippet: posix2.join(caddyDir, `${input.name}.caddy`)
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// src/update-page.ts
|
|
399
|
+
function renderUpdatePage() {
|
|
400
|
+
return `<!doctype html>
|
|
401
|
+
<html lang="en">
|
|
402
|
+
<head>
|
|
403
|
+
<meta charset="utf-8">
|
|
404
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
405
|
+
<meta http-equiv="refresh" content="10">
|
|
406
|
+
<title>Updates in progress</title>
|
|
407
|
+
<style>
|
|
408
|
+
: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; }
|
|
409
|
+
* { box-sizing: border-box; }
|
|
410
|
+
body { margin: 0; min-height: 100vh; min-height: 100svh; display: grid; place-items: center; padding: 48px 28px; -webkit-font-smoothing: antialiased; }
|
|
411
|
+
main { width: 100%; max-width: 480px; }
|
|
412
|
+
.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; }
|
|
413
|
+
.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; }
|
|
414
|
+
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; }
|
|
415
|
+
.description { margin: 0; max-width: 380px; color: var(--muted); font-size: 15px; line-height: 1.8; text-wrap: pretty; }
|
|
416
|
+
.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); }
|
|
417
|
+
.footer p { margin: 0; font-size: 12px; line-height: 1.6; }
|
|
418
|
+
.footer .interval { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 10px; letter-spacing: 0.02em; }
|
|
419
|
+
@keyframes spin { to { transform: rotate(360deg); } }
|
|
420
|
+
@media (prefers-reduced-motion: reduce) { .loader { animation: none; } }
|
|
421
|
+
@media (prefers-color-scheme: dark) {
|
|
422
|
+
:root { background: #0a0a0a; color: #f5f5f5; --muted: #999; --line: #262626; --surface: #111; --track: #444; }
|
|
423
|
+
}
|
|
424
|
+
</style>
|
|
425
|
+
</head>
|
|
426
|
+
<body>
|
|
427
|
+
<main>
|
|
428
|
+
<div class="status"><span class="loader" aria-hidden="true"></span>Site update</div>
|
|
429
|
+
<h1>Updates in progress</h1>
|
|
430
|
+
<p class="description">We\u2019re making a few updates. The site should be back soon. Thanks for your patience.</p>
|
|
431
|
+
<div class="footer">
|
|
432
|
+
<p>This page will reconnect automatically.</p>
|
|
433
|
+
<p class="interval">Retrying every 10s</p>
|
|
434
|
+
</div>
|
|
435
|
+
</main>
|
|
436
|
+
</body>
|
|
437
|
+
</html>`;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// src/render.ts
|
|
441
|
+
var GENERATED = "Generated by sixb deploy. Changes are replaced on the next deploy.";
|
|
442
|
+
function renderProcessManifest(release, layout) {
|
|
443
|
+
const sixb = `${layout.project}/node_modules/.bin/sixb`;
|
|
444
|
+
return {
|
|
445
|
+
version: 1,
|
|
446
|
+
name: release.name,
|
|
447
|
+
cwd: layout.project,
|
|
448
|
+
runDir: layout.runDir,
|
|
449
|
+
logDir: layout.logDir,
|
|
450
|
+
releasePath: layout.releaseRecord,
|
|
451
|
+
services: release.services.map((service) => ({
|
|
452
|
+
name: service.name,
|
|
453
|
+
processName: `${release.name}-${service.name}`,
|
|
454
|
+
command: layout.bun,
|
|
455
|
+
args: service.command.program === "sixb" ? [sixb, ...service.command.args] : [...service.command.args],
|
|
456
|
+
env: service.env,
|
|
457
|
+
instances: service.instances,
|
|
458
|
+
killTimeoutMs: service.process.killTimeoutMs,
|
|
459
|
+
restartDelayMs: service.process.restartDelayMs,
|
|
460
|
+
...service.process.maxMemory ? { maxMemory: service.process.maxMemory } : {}
|
|
461
|
+
}))
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
function renderCtl(layout) {
|
|
465
|
+
return [
|
|
466
|
+
"#!/bin/sh",
|
|
467
|
+
`# ${GENERATED}`,
|
|
468
|
+
`exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} "$@" --manifest ${shellQuote(layout.manifest)}`,
|
|
469
|
+
""
|
|
470
|
+
].join(`
|
|
471
|
+
`);
|
|
472
|
+
}
|
|
473
|
+
function renderUnit(release, layout) {
|
|
474
|
+
const stopSeconds = Math.ceil(Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000) + 10;
|
|
475
|
+
return [
|
|
476
|
+
`# ${GENERATED}`,
|
|
477
|
+
"[Unit]",
|
|
478
|
+
`Description=Sixb deployment ${release.name}`,
|
|
479
|
+
"",
|
|
480
|
+
"[Service]",
|
|
481
|
+
"Type=simple",
|
|
482
|
+
`WorkingDirectory=${systemdValue(layout.project)}`,
|
|
483
|
+
`Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,
|
|
484
|
+
`ExecStart=${systemdValue(layout.ctl)} supervise`,
|
|
485
|
+
"Restart=always",
|
|
486
|
+
"RestartSec=2",
|
|
487
|
+
"KillSignal=SIGTERM",
|
|
488
|
+
`TimeoutStopSec=${stopSeconds}`,
|
|
489
|
+
"",
|
|
490
|
+
"[Install]",
|
|
491
|
+
"WantedBy=default.target",
|
|
492
|
+
""
|
|
493
|
+
].join(`
|
|
494
|
+
`);
|
|
495
|
+
}
|
|
496
|
+
function renderCaddySnippet(release) {
|
|
497
|
+
const sites = release.services.flatMap((service) => {
|
|
498
|
+
if (!service.http)
|
|
499
|
+
return [];
|
|
500
|
+
const pages = service.name === "app" || service.name === "atlas";
|
|
501
|
+
return [
|
|
502
|
+
[
|
|
503
|
+
`${service.http.domain} {`,
|
|
504
|
+
` reverse_proxy ${service.http.host}:${service.http.port}`,
|
|
505
|
+
...pages ? updatePageOnProxyErrors() : [],
|
|
506
|
+
"}"
|
|
507
|
+
].join(`
|
|
508
|
+
`)
|
|
509
|
+
];
|
|
510
|
+
});
|
|
511
|
+
return [`# ${GENERATED}`, "", sites.join(`
|
|
512
|
+
|
|
513
|
+
`), ""].join(`
|
|
514
|
+
`);
|
|
515
|
+
}
|
|
516
|
+
function updatePageOnProxyErrors() {
|
|
517
|
+
return [
|
|
518
|
+
"\thandle_errors 502 503 504 {",
|
|
519
|
+
"\t\t@page {",
|
|
520
|
+
"\t\t\tmethod GET",
|
|
521
|
+
"\t\t\theader Accept *text/html*",
|
|
522
|
+
"\t\t}",
|
|
523
|
+
"\t\thandle @page {",
|
|
524
|
+
'\t\t\theader Content-Type "text/html; charset=utf-8"',
|
|
525
|
+
'\t\t\theader Cache-Control "no-store"',
|
|
526
|
+
'\t\t\theader Retry-After "10"',
|
|
527
|
+
"\t\t\trespond 503 {",
|
|
528
|
+
"\t\t\t\tbody <<HTML",
|
|
529
|
+
...renderUpdatePage().split(`
|
|
530
|
+
`).map((line) => ` ${line}`),
|
|
531
|
+
"\t\t\t\tHTML",
|
|
532
|
+
"\t\t\t}",
|
|
533
|
+
"\t\t}",
|
|
534
|
+
"\t\thandle {",
|
|
535
|
+
'\t\t\trespond "Service temporarily unavailable" {err.status_code}',
|
|
536
|
+
"\t\t}",
|
|
537
|
+
"\t}"
|
|
538
|
+
];
|
|
539
|
+
}
|
|
540
|
+
function systemdValue(value) {
|
|
541
|
+
return value.replace(/%/g, "%%").replace(/\s/g, "\\x20");
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/scripts.ts
|
|
545
|
+
var STEP_MARKER = "__SIXB_STEP__";
|
|
546
|
+
function renderPrepareScript(name, commit) {
|
|
547
|
+
return [
|
|
548
|
+
`root="$HOME"/${shellQuote(name)}`,
|
|
549
|
+
'mkdir -p "$root/deploy/incoming"',
|
|
550
|
+
`incoming="$(mktemp -d "$root/deploy/incoming/${commit.slice(0, 12)}.XXXXXX")"`,
|
|
551
|
+
'chmod 755 "$incoming"',
|
|
552
|
+
`printf '%s\\n%s\\n' "$HOME" "$incoming"`
|
|
553
|
+
].join(`
|
|
554
|
+
`);
|
|
555
|
+
}
|
|
556
|
+
function renderReceiveScript(incoming, path) {
|
|
557
|
+
const directory = path === "." ? incoming : `${incoming}/${path}`;
|
|
558
|
+
return `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`;
|
|
559
|
+
}
|
|
560
|
+
function renderDeployScript(input) {
|
|
561
|
+
const { release, layout } = input;
|
|
562
|
+
const api = release.services.find((service) => service.http?.readinessPath);
|
|
563
|
+
const steps = [
|
|
564
|
+
{ label: "Apply files", body: renderApplyFiles(layout, input.incoming) },
|
|
565
|
+
{ label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },
|
|
566
|
+
{ label: "Install dependencies", body: renderInstallDependencies() },
|
|
567
|
+
...release.steps.build.map((command) => runStep(command)),
|
|
568
|
+
{ label: "Write services", body: renderWriteServices(release, layout) },
|
|
569
|
+
{ label: "Update routes", body: renderUpdateRoutes(release, layout) },
|
|
570
|
+
{ label: "Stop services", body: renderStopServices() },
|
|
571
|
+
...release.steps.beforeStart.map((command) => runStep(command)),
|
|
572
|
+
{ label: "Start services", body: renderStartServices() },
|
|
573
|
+
{
|
|
574
|
+
label: "Check services",
|
|
575
|
+
body: renderCheckServices(api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null)
|
|
576
|
+
},
|
|
577
|
+
{
|
|
578
|
+
label: "Record release",
|
|
579
|
+
body: writeFileCommand(layout.releaseRecord, `${JSON.stringify(input.record)}
|
|
580
|
+
`)
|
|
581
|
+
}
|
|
582
|
+
];
|
|
583
|
+
const script = [
|
|
584
|
+
"set -euo pipefail",
|
|
585
|
+
"main() {",
|
|
586
|
+
renderEnvironment(release, layout),
|
|
587
|
+
renderTakeLock(layout),
|
|
588
|
+
...steps.flatMap((step, index) => [
|
|
589
|
+
`printf '\\n%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} start`,
|
|
590
|
+
step.body,
|
|
591
|
+
`printf '%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} done`
|
|
592
|
+
]),
|
|
593
|
+
"}",
|
|
594
|
+
"main </dev/null",
|
|
595
|
+
""
|
|
596
|
+
].join(`
|
|
597
|
+
`);
|
|
598
|
+
return { labels: steps.map((step) => step.label), script };
|
|
599
|
+
}
|
|
600
|
+
function renderEnvironment(release, layout) {
|
|
601
|
+
const variables = {
|
|
602
|
+
ROOT: layout.root,
|
|
603
|
+
CODE: layout.code,
|
|
604
|
+
PROJECT: layout.project,
|
|
605
|
+
DEPLOY: layout.deployDir,
|
|
606
|
+
BUN: layout.bun,
|
|
607
|
+
BUN_DIR: layout.bunDir,
|
|
608
|
+
BUN_VERSION: release.bunVersion,
|
|
609
|
+
CTL: layout.ctl,
|
|
610
|
+
UNIT: layout.unitName,
|
|
611
|
+
UNIT_PATH: layout.unit,
|
|
612
|
+
CADDY_DIR: layout.caddyDir,
|
|
613
|
+
CADDY_SNIPPET: layout.caddySnippet
|
|
614
|
+
};
|
|
615
|
+
return [
|
|
616
|
+
...Object.entries(variables).map(([name, value]) => `${name}=${shellQuote(value)}`),
|
|
617
|
+
...Object.entries(release.env).map(([name, value]) => `export ${name}=${shellQuote(value)}`),
|
|
618
|
+
'export PATH="$BUN_DIR:$PATH"',
|
|
619
|
+
'printenv XDG_RUNTIME_DIR > /dev/null || export XDG_RUNTIME_DIR="/run/user/$(id -u)"'
|
|
620
|
+
].join(`
|
|
621
|
+
`);
|
|
622
|
+
}
|
|
623
|
+
function renderTakeLock(layout) {
|
|
624
|
+
return [
|
|
625
|
+
`exec 9>${shellQuote(layout.lock)}`,
|
|
626
|
+
"if ! flock -n 9; then",
|
|
627
|
+
' echo "Waiting for another deploy of this project to finish\u2026"',
|
|
628
|
+
"fi",
|
|
629
|
+
"if ! flock -w 600 9; then",
|
|
630
|
+
' echo "Another deploy of this project has held its lock for 10 minutes." >&2',
|
|
631
|
+
" exit 1",
|
|
632
|
+
"fi"
|
|
633
|
+
].join(`
|
|
634
|
+
`);
|
|
635
|
+
}
|
|
636
|
+
function renderApplyFiles(layout, incoming) {
|
|
637
|
+
return [
|
|
638
|
+
`incoming=${shellQuote(incoming)}`,
|
|
639
|
+
`files=${shellQuote(layout.fileList)}`,
|
|
640
|
+
`code=${shellQuote(layout.code)}`,
|
|
641
|
+
'listed="$incoming.files"',
|
|
642
|
+
'(cd "$incoming" && find . \\( -type f -o -type l \\) ! -name .env | LC_ALL=C sort) > "$listed"',
|
|
643
|
+
'mkdir -p "$code"',
|
|
644
|
+
'if [ -f "$files" ]; then',
|
|
645
|
+
' LC_ALL=C comm -23 "$files" "$listed" | while IFS= read -r path; do',
|
|
646
|
+
' rm -f "$code/$path"',
|
|
647
|
+
' dir="$(dirname "$code/$path")"',
|
|
648
|
+
' while [ "$dir" != "$code" ] && [ "$dir" != "$code/." ] && rmdir "$dir" 2>/dev/null; do',
|
|
649
|
+
' dir="$(dirname "$dir")"',
|
|
650
|
+
" done",
|
|
651
|
+
" done",
|
|
652
|
+
"fi",
|
|
653
|
+
`(cd "$incoming" && tar -c -f - --exclude=.env .) | (cd "$code" && tar -x -f -)`,
|
|
654
|
+
'mv "$listed" "$files"',
|
|
655
|
+
'rm -rf "$incoming"',
|
|
656
|
+
'find "$(dirname "$incoming")" -mindepth 1 -maxdepth 1 -mmin +1440 -exec rm -rf {} + 2>/dev/null || true'
|
|
657
|
+
].join(`
|
|
658
|
+
`);
|
|
659
|
+
}
|
|
660
|
+
function renderInstallBun(version) {
|
|
661
|
+
const release = `https://github.com/oven-sh/bun/releases/download/bun-v${version}`;
|
|
662
|
+
return [
|
|
663
|
+
'if [ ! -x "$BUN" ]; then',
|
|
664
|
+
' case "$(uname -m)" in',
|
|
665
|
+
" x86_64 | amd64) arch=x64 ;;",
|
|
666
|
+
" aarch64 | arm64) arch=aarch64 ;;",
|
|
667
|
+
' *) echo "Bun has no Linux build for $(uname -m)." >&2; exit 1 ;;',
|
|
668
|
+
" esac",
|
|
669
|
+
' if [ "$arch" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi',
|
|
670
|
+
' asset="bun-linux-$arch"',
|
|
671
|
+
' download="$(mktemp -d)"',
|
|
672
|
+
` curl -fsSL --retry 3 -o "$download/$asset.zip" ${shellQuote(release)}"/$asset.zip"`,
|
|
673
|
+
` curl -fsSL --retry 3 -o "$download/SHASUMS256.txt" ${shellQuote(release)}/SHASUMS256.txt`,
|
|
674
|
+
' (cd "$download" && grep " $asset.zip\\$" SHASUMS256.txt | sha256sum -c --quiet -)',
|
|
675
|
+
' unzip -q "$download/$asset.zip" -d "$download"',
|
|
676
|
+
' mkdir -p "$BUN_DIR"',
|
|
677
|
+
' mv "$download/$asset/bun" "$BUN"',
|
|
678
|
+
' rm -rf "$download"',
|
|
679
|
+
"fi",
|
|
680
|
+
'"$BUN" --version'
|
|
681
|
+
].join(`
|
|
682
|
+
`);
|
|
683
|
+
}
|
|
684
|
+
function renderInstallDependencies() {
|
|
685
|
+
return [
|
|
686
|
+
'cd "$PROJECT"',
|
|
687
|
+
'"$BUN" install --frozen-lockfile',
|
|
688
|
+
"for bin in sixb sixb-deploy-ssh; do",
|
|
689
|
+
' if [ ! -e "$PROJECT/node_modules/.bin/$bin" ]; then',
|
|
690
|
+
' package="@sixb/cli"; [ "$bin" = sixb ] || package="@sixb/deploy-ssh"',
|
|
691
|
+
' echo "$package is not installed. Add it to the project dependencies." >&2',
|
|
692
|
+
" exit 1",
|
|
693
|
+
" fi",
|
|
694
|
+
"done"
|
|
695
|
+
].join(`
|
|
696
|
+
`);
|
|
697
|
+
}
|
|
698
|
+
function runStep(command) {
|
|
699
|
+
const program = command.program === "sixb" ? '"$PROJECT/node_modules/.bin/sixb"' : "";
|
|
700
|
+
return {
|
|
701
|
+
label: [command.program, ...command.args].join(" "),
|
|
702
|
+
body: [
|
|
703
|
+
'cd "$PROJECT"',
|
|
704
|
+
`"$BUN" ${program} ${command.args.map(shellQuote).join(" ")}`.replace(/ {2,}/g, " ")
|
|
705
|
+
].join(`
|
|
706
|
+
`)
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function renderStopServices() {
|
|
710
|
+
return [
|
|
711
|
+
'if systemctl --user is-active --quiet "$UNIT"; then',
|
|
712
|
+
' systemctl --user stop "$UNIT"',
|
|
713
|
+
"else",
|
|
714
|
+
" echo 'Services were not running.'",
|
|
715
|
+
"fi"
|
|
716
|
+
].join(`
|
|
717
|
+
`);
|
|
718
|
+
}
|
|
719
|
+
function renderWriteServices(release, layout) {
|
|
720
|
+
return [
|
|
721
|
+
writeFileCommand(layout.manifest, `${JSON.stringify(renderProcessManifest(release, layout), null, 2)}
|
|
722
|
+
`),
|
|
723
|
+
writeFileCommand(layout.ctl, renderCtl(layout)),
|
|
724
|
+
'chmod 755 "$CTL"',
|
|
725
|
+
'mkdir -p "$(dirname "$UNIT_PATH")"',
|
|
726
|
+
writeFileCommand(`${layout.unit}.new`, renderUnit(release, layout)),
|
|
727
|
+
'if cmp -s "$UNIT_PATH.new" "$UNIT_PATH"; then',
|
|
728
|
+
' rm -f "$UNIT_PATH.new"',
|
|
729
|
+
"else",
|
|
730
|
+
' mv "$UNIT_PATH.new" "$UNIT_PATH"',
|
|
731
|
+
" systemctl --user daemon-reload",
|
|
732
|
+
' systemctl --user enable "$UNIT"',
|
|
733
|
+
"fi"
|
|
734
|
+
].join(`
|
|
735
|
+
`);
|
|
736
|
+
}
|
|
737
|
+
function renderUpdateRoutes(release, layout) {
|
|
738
|
+
return [
|
|
739
|
+
`new=${shellQuote(`${layout.deployDir}/Caddyfile`)}`,
|
|
740
|
+
writeFileCommand(`${layout.deployDir}/Caddyfile`, renderCaddySnippet(release)),
|
|
741
|
+
'if cmp -s "$new" "$CADDY_SNIPPET"; then',
|
|
742
|
+
" echo 'Routes unchanged.'",
|
|
743
|
+
"else",
|
|
744
|
+
' if [ ! -w "$CADDY_DIR" ]; then',
|
|
745
|
+
' echo "$CADDY_DIR is missing or not writable, so this server is not set up for sixb deploy." >&2',
|
|
746
|
+
" exit 1",
|
|
747
|
+
" fi",
|
|
748
|
+
' previous="$DEPLOY/Caddyfile.previous"',
|
|
749
|
+
' rm -f "$previous"',
|
|
750
|
+
' if [ -f "$CADDY_SNIPPET" ]; then cp "$CADDY_SNIPPET" "$previous"; fi',
|
|
751
|
+
' cp "$new" "$CADDY_SNIPPET"',
|
|
752
|
+
' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > "$DEPLOY/caddy-validate.log" 2>&1; then',
|
|
753
|
+
' if [ -f "$previous" ]; then cp "$previous" "$CADDY_SNIPPET"; else rm -f "$CADDY_SNIPPET"; fi',
|
|
754
|
+
' tail -n 20 "$DEPLOY/caddy-validate.log" >&2',
|
|
755
|
+
" echo 'Caddy rejected the routes; the previous ones are back in place.' >&2",
|
|
756
|
+
" exit 1",
|
|
757
|
+
" fi",
|
|
758
|
+
" sudo -n /usr/bin/systemctl reload caddy",
|
|
759
|
+
"fi"
|
|
760
|
+
].join(`
|
|
761
|
+
`);
|
|
762
|
+
}
|
|
763
|
+
function renderStartServices() {
|
|
764
|
+
return ['systemctl --user restart "$UNIT"', 'systemctl --user is-active --quiet "$UNIT"'].join(`
|
|
765
|
+
`);
|
|
766
|
+
}
|
|
767
|
+
function renderCheckServices(readinessUrl) {
|
|
768
|
+
const waitForApi = readinessUrl ? [
|
|
769
|
+
`ready_url=${shellQuote(readinessUrl)}`,
|
|
770
|
+
"ready=0",
|
|
771
|
+
"for attempt in $(seq 1 90); do",
|
|
772
|
+
` if "$BUN" -e 'const r = await fetch(process.argv[1]).catch(() => null); process.exit(r?.ok ? 0 : 1)' "$ready_url" 2>/dev/null; then`,
|
|
773
|
+
" ready=1",
|
|
774
|
+
" break",
|
|
775
|
+
" fi",
|
|
776
|
+
" sleep 1",
|
|
777
|
+
"done",
|
|
778
|
+
'if [ "$ready" != 1 ]; then',
|
|
779
|
+
' echo "The API did not answer $ready_url within 90 seconds. Its latest log lines:" >&2',
|
|
780
|
+
' "$CTL" logs api --tail 30 >&2 || true',
|
|
781
|
+
" exit 1",
|
|
782
|
+
"fi"
|
|
783
|
+
] : [];
|
|
784
|
+
return [...waitForApi, "sleep 5", '"$CTL" status --check'].join(`
|
|
785
|
+
`);
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// src/server/logs.ts
|
|
789
|
+
var MAX_LOG_BYTES = 20 * 1024 * 1024;
|
|
790
|
+
var RECENT_BYTES = 256 * 1024;
|
|
791
|
+
var TERMINAL_CONTROL = /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[@-Z\\-_])/g;
|
|
792
|
+
function stripTerminalControl(line) {
|
|
793
|
+
return line.replace(TERMINAL_CONTROL, "");
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// src/transport.ts
|
|
797
|
+
import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
|
|
798
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
799
|
+
import { join as join2 } from "path";
|
|
800
|
+
class RemoteScriptError extends Error {
|
|
801
|
+
exitCode;
|
|
802
|
+
constructor(message, exitCode) {
|
|
803
|
+
super(message);
|
|
804
|
+
this.name = "RemoteScriptError";
|
|
805
|
+
this.exitCode = exitCode;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
var OUTPUT_TAIL = 20;
|
|
809
|
+
|
|
810
|
+
class SshShell {
|
|
811
|
+
destination;
|
|
812
|
+
controlDir;
|
|
813
|
+
constructor(destination, controlDir) {
|
|
814
|
+
this.destination = destination;
|
|
815
|
+
this.controlDir = controlDir;
|
|
816
|
+
}
|
|
817
|
+
static async open(destination) {
|
|
818
|
+
const controlDir = await mkdtemp2(join2(tmpdir2(), "sixb-ssh-"));
|
|
819
|
+
const shell = new SshShell(destination, controlDir);
|
|
820
|
+
try {
|
|
821
|
+
await runProcess(["ssh", ...shell.options(), "-M", "-N", "-f", destination], {});
|
|
822
|
+
} catch (error) {
|
|
823
|
+
await rm2(controlDir, { recursive: true, force: true });
|
|
824
|
+
throw sshError(destination, error);
|
|
825
|
+
}
|
|
826
|
+
return shell;
|
|
827
|
+
}
|
|
828
|
+
async run(script, options = {}) {
|
|
829
|
+
const inline = options.stdin !== undefined || options.terminal === true;
|
|
830
|
+
const command = inline ? ["bash", "-c", shellQuote(script)] : ["bash", "-s"];
|
|
831
|
+
try {
|
|
832
|
+
await runProcess([
|
|
833
|
+
"ssh",
|
|
834
|
+
...this.options(),
|
|
835
|
+
...options.terminal ? ["-tt"] : [],
|
|
836
|
+
this.destination,
|
|
837
|
+
command.join(" ")
|
|
838
|
+
], {
|
|
839
|
+
...options,
|
|
840
|
+
...inline ? {} : { stdin: new Blob([script]).stream() }
|
|
841
|
+
});
|
|
842
|
+
} catch (error) {
|
|
843
|
+
throw sshError(this.destination, error);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
async close() {
|
|
847
|
+
await runProcess(["ssh", ...this.options(), "-O", "exit", this.destination], {}).catch(() => {});
|
|
848
|
+
await rm2(this.controlDir, { recursive: true, force: true });
|
|
849
|
+
}
|
|
850
|
+
options() {
|
|
851
|
+
return [
|
|
852
|
+
"-o",
|
|
853
|
+
"BatchMode=yes",
|
|
854
|
+
"-o",
|
|
855
|
+
"ConnectTimeout=15",
|
|
856
|
+
"-o",
|
|
857
|
+
"ServerAliveInterval=15",
|
|
858
|
+
"-o",
|
|
859
|
+
"ControlMaster=auto",
|
|
860
|
+
"-o",
|
|
861
|
+
"ControlPersist=60",
|
|
862
|
+
"-o",
|
|
863
|
+
"LogLevel=ERROR",
|
|
864
|
+
"-S",
|
|
865
|
+
join2(this.controlDir, "control")
|
|
866
|
+
];
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
async function runProcess(command, options) {
|
|
870
|
+
if (options.terminal) {
|
|
871
|
+
const child = Bun.spawn([...command], { stdio: ["inherit", "inherit", "inherit"] });
|
|
872
|
+
const exitCode = await child.exited;
|
|
873
|
+
if (exitCode !== 0)
|
|
874
|
+
throw new RemoteScriptError(`exited with code ${exitCode}`, exitCode);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
const child = Bun.spawn([...command], {
|
|
878
|
+
stdin: options.stdin ? "pipe" : "ignore",
|
|
879
|
+
stdout: "pipe",
|
|
880
|
+
stderr: "pipe",
|
|
881
|
+
env: { ...process.env, ...options.env }
|
|
882
|
+
});
|
|
883
|
+
const tail = [];
|
|
884
|
+
const onLine = (stream) => (line) => {
|
|
885
|
+
tail.push(line);
|
|
886
|
+
if (tail.length > OUTPUT_TAIL)
|
|
887
|
+
tail.shift();
|
|
888
|
+
options.onLine?.(line, stream);
|
|
889
|
+
};
|
|
890
|
+
const [exitCode] = await Promise.all([
|
|
891
|
+
child.exited,
|
|
892
|
+
options.stdin && child.stdin ? pump(options.stdin, child.stdin) : undefined,
|
|
893
|
+
readLines(child.stdout, onLine("stdout")),
|
|
894
|
+
readLines(child.stderr, onLine("stderr"))
|
|
895
|
+
]);
|
|
896
|
+
if (exitCode !== 0) {
|
|
897
|
+
throw new RemoteScriptError(tail.length > 0 ? tail.join(`
|
|
898
|
+
`) : `exited with code ${exitCode}`, exitCode);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
async function pump(source, sink) {
|
|
902
|
+
const reader = source.getReader();
|
|
903
|
+
try {
|
|
904
|
+
for (let chunk = await reader.read();!chunk.done; chunk = await reader.read()) {
|
|
905
|
+
sink.write(chunk.value);
|
|
906
|
+
await sink.flush();
|
|
907
|
+
}
|
|
908
|
+
} finally {
|
|
909
|
+
await sink.end();
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
async function readLines(stream, onLine) {
|
|
913
|
+
const reader = stream.getReader();
|
|
914
|
+
const decoder = new TextDecoder;
|
|
915
|
+
let buffer = "";
|
|
916
|
+
for (let chunk = await reader.read();!chunk.done; chunk = await reader.read()) {
|
|
917
|
+
buffer += decoder.decode(chunk.value, { stream: true });
|
|
918
|
+
const lines = buffer.split(/\r?\n/);
|
|
919
|
+
buffer = lines.pop() ?? "";
|
|
920
|
+
for (const line of lines)
|
|
921
|
+
onLine(line);
|
|
922
|
+
}
|
|
923
|
+
buffer += decoder.decode();
|
|
924
|
+
if (buffer)
|
|
925
|
+
onLine(buffer);
|
|
926
|
+
}
|
|
927
|
+
function sshError(destination, error) {
|
|
928
|
+
if (!(error instanceof RemoteScriptError) || error.exitCode !== 255) {
|
|
929
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
930
|
+
}
|
|
931
|
+
const output = error.message;
|
|
932
|
+
const host = destination.split("@").at(-1) ?? destination;
|
|
933
|
+
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.`;
|
|
934
|
+
return new RemoteScriptError(`[SshTarget] ${reason}
|
|
935
|
+
${output}`, error.exitCode);
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// src/operations.ts
|
|
939
|
+
var NOT_DEPLOYED = "__SIXB_NOT_DEPLOYED__";
|
|
940
|
+
async function deployRelease(shell, user, release, source, context) {
|
|
941
|
+
const prepared = await capture(shell, renderPrepareScript(release.name, source.commit));
|
|
942
|
+
const [home, incoming] = prepared;
|
|
943
|
+
if (!home || !incoming) {
|
|
944
|
+
throw new Error("[SshTarget] The server did not report its home directory.");
|
|
945
|
+
}
|
|
946
|
+
const layout = deploymentLayout({
|
|
947
|
+
home,
|
|
948
|
+
user,
|
|
949
|
+
name: release.name,
|
|
950
|
+
projectPath: source.projectPath,
|
|
951
|
+
bunVersion: release.bunVersion
|
|
952
|
+
});
|
|
953
|
+
const { labels, script } = renderDeployScript({
|
|
954
|
+
release,
|
|
955
|
+
layout,
|
|
956
|
+
incoming,
|
|
957
|
+
record: {
|
|
958
|
+
commit: source.commit,
|
|
959
|
+
ref: source.ref,
|
|
960
|
+
deployedAt: new Date().toISOString(),
|
|
961
|
+
deployedBy: context.deployedBy
|
|
962
|
+
}
|
|
963
|
+
});
|
|
964
|
+
context.report({ type: "steps", labels: ["Upload source", ...labels] });
|
|
965
|
+
context.report({ type: "step", index: 0, status: "running" });
|
|
966
|
+
for (const archive of source.archives) {
|
|
967
|
+
await shell.run(renderReceiveScript(incoming, archive.path), { stdin: archive.open() });
|
|
968
|
+
}
|
|
969
|
+
context.report({ type: "step", index: 0, status: "done" });
|
|
970
|
+
await runReportingSteps(shell, script, context);
|
|
971
|
+
}
|
|
972
|
+
async function runReportingSteps(shell, script, context) {
|
|
973
|
+
const run = shell.run(script, {
|
|
974
|
+
onLine: (line) => {
|
|
975
|
+
const [marker, index, status] = line.split("\t");
|
|
976
|
+
if (marker === STEP_MARKER && (status === "start" || status === "done")) {
|
|
977
|
+
const step = Number(index) + 1;
|
|
978
|
+
context.report({
|
|
979
|
+
type: "step",
|
|
980
|
+
index: step,
|
|
981
|
+
status: status === "start" ? "running" : "done"
|
|
982
|
+
});
|
|
983
|
+
} else {
|
|
984
|
+
const output = stripTerminalControl(line);
|
|
985
|
+
if (output.trim())
|
|
986
|
+
context.report({ type: "output", line: output });
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
try {
|
|
991
|
+
await run;
|
|
992
|
+
} catch (error) {
|
|
993
|
+
if (error instanceof RemoteScriptError && error.exitCode !== 255) {
|
|
994
|
+
throw new Error(`[SshTarget] The step exited with code ${error.exitCode}.`);
|
|
995
|
+
}
|
|
996
|
+
throw error;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
async function readStatus(shell, name) {
|
|
1000
|
+
const lines = await capture(shell, ctlScript(name, ["status", "--json"], { allowMissing: true }));
|
|
1001
|
+
const report = lines.find((line) => line.startsWith("{"));
|
|
1002
|
+
if (lines.includes(NOT_DEPLOYED) || !report) {
|
|
1003
|
+
return { release: null, running: false, processes: [] };
|
|
1004
|
+
}
|
|
1005
|
+
return JSON.parse(report);
|
|
1006
|
+
}
|
|
1007
|
+
async function streamLogs(shell, name, options) {
|
|
1008
|
+
const args = [
|
|
1009
|
+
"logs",
|
|
1010
|
+
...options.service ? [options.service] : [],
|
|
1011
|
+
"--tail",
|
|
1012
|
+
String(options.tail),
|
|
1013
|
+
...options.follow ? ["--follow"] : []
|
|
1014
|
+
];
|
|
1015
|
+
await shell.run(ctlScript(name, args), {
|
|
1016
|
+
...options.terminal ? { terminal: true } : { onLine: (line) => options.write(line) }
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
async function controlServices(shell, name, action, service) {
|
|
1020
|
+
await shell.run(ctlScript(name, [action, ...service ? [service] : []]));
|
|
1021
|
+
}
|
|
1022
|
+
function ctlScript(name, args, options = {}) {
|
|
1023
|
+
return [
|
|
1024
|
+
`ctl="$HOME"/${shellQuote(name)}/deploy/ctl`,
|
|
1025
|
+
'if [ ! -x "$ctl" ]; then',
|
|
1026
|
+
options.allowMissing ? ` echo ${NOT_DEPLOYED}; exit 0` : ` echo "Nothing named ${name} is deployed on this server yet." >&2; exit 1`,
|
|
1027
|
+
"fi",
|
|
1028
|
+
`exec "$ctl" ${args.map(shellQuote).join(" ")}`
|
|
1029
|
+
].join(`
|
|
1030
|
+
`);
|
|
1031
|
+
}
|
|
1032
|
+
async function capture(shell, script) {
|
|
1033
|
+
const lines = [];
|
|
1034
|
+
await shell.run(script, {
|
|
1035
|
+
onLine: (line, stream) => {
|
|
1036
|
+
if (stream === "stdout")
|
|
1037
|
+
lines.push(line);
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
return lines;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// src/setup.ts
|
|
1044
|
+
import { access } from "fs/promises";
|
|
1045
|
+
var PACKAGED_CADDYFILE = "The Caddyfile is an easy way to configure your Caddy web server.";
|
|
1046
|
+
function renderAdminScript(input) {
|
|
1047
|
+
const user = shellQuote(input.user);
|
|
1048
|
+
return [
|
|
1049
|
+
"set -euo pipefail",
|
|
1050
|
+
`deploy_user=${user}`,
|
|
1051
|
+
`public_key=${shellQuote(input.publicKey)}`,
|
|
1052
|
+
`admin_login=${shellQuote(input.admin)}`,
|
|
1053
|
+
'step() { printf "\\n== %s\\n" "$1"; }',
|
|
1054
|
+
'quiet() { log="$(mktemp)"; if "$@" > "$log" 2>&1; then rm -f "$log"; else status=$?; tail -n 20 "$log" >&2; rm -f "$log"; return "$status"; fi; }',
|
|
1055
|
+
"",
|
|
1056
|
+
'step "Server"',
|
|
1057
|
+
"if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then",
|
|
1058
|
+
' echo "sixb deploy needs an Ubuntu or Debian server with systemd." >&2',
|
|
1059
|
+
" exit 1",
|
|
1060
|
+
"fi",
|
|
1061
|
+
'. /etc/os-release && echo "$PRETTY_NAME"',
|
|
1062
|
+
"",
|
|
1063
|
+
'step "Packages"',
|
|
1064
|
+
"export DEBIAN_FRONTEND=noninteractive",
|
|
1065
|
+
'missing=""',
|
|
1066
|
+
"for package in git curl unzip ca-certificates gnupg; do",
|
|
1067
|
+
' dpkg -l "$package" 2> /dev/null | grep -q "^ii" || missing="$missing $package"',
|
|
1068
|
+
"done",
|
|
1069
|
+
'if [ -n "$missing" ]; then',
|
|
1070
|
+
' echo "Installing$missing"',
|
|
1071
|
+
" quiet apt-get update",
|
|
1072
|
+
" quiet apt-get install -y $missing",
|
|
1073
|
+
"fi",
|
|
1074
|
+
"if ! command -v caddy > /dev/null; then",
|
|
1075
|
+
' echo "Installing caddy"',
|
|
1076
|
+
" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |",
|
|
1077
|
+
" gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
|
|
1078
|
+
" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
|
|
1079
|
+
" quiet apt-get update",
|
|
1080
|
+
" quiet apt-get install -y caddy",
|
|
1081
|
+
"fi",
|
|
1082
|
+
`echo "git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)"`,
|
|
1083
|
+
"",
|
|
1084
|
+
'step "Deploy user $deploy_user"',
|
|
1085
|
+
'id "$deploy_user" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group "$deploy_user"',
|
|
1086
|
+
'home="$(getent passwd "$deploy_user" | cut -d: -f6)"',
|
|
1087
|
+
'chmod 750 "$home"',
|
|
1088
|
+
'install -d -m 0700 -o "$deploy_user" -g "$deploy_user" "$home/.ssh"',
|
|
1089
|
+
'touch "$home/.ssh/authorized_keys"',
|
|
1090
|
+
'grep -qxF "$public_key" "$home/.ssh/authorized_keys" || echo "$public_key" >> "$home/.ssh/authorized_keys"',
|
|
1091
|
+
'chown "$deploy_user:$deploy_user" "$home/.ssh/authorized_keys"',
|
|
1092
|
+
'chmod 0600 "$home/.ssh/authorized_keys"',
|
|
1093
|
+
'loginctl enable-linger "$deploy_user"',
|
|
1094
|
+
'grep -qs XDG_RUNTIME_DIR "$home/.profile" ||',
|
|
1095
|
+
` echo 'export XDG_RUNTIME_DIR="/run/user/$(id -u)"' >> "$home/.profile"`,
|
|
1096
|
+
'chown "$deploy_user:$deploy_user" "$home/.profile"',
|
|
1097
|
+
'if [ "$admin_login" != root ]; then usermod -aG "$deploy_user" "$admin_login"; fi',
|
|
1098
|
+
'echo "$home, key-only, services start at boot"',
|
|
1099
|
+
"",
|
|
1100
|
+
'step "Caddy reload"',
|
|
1101
|
+
"groupadd -f sixb-deploy",
|
|
1102
|
+
'usermod -aG sixb-deploy "$deploy_user"',
|
|
1103
|
+
'sudoers="$(mktemp)"',
|
|
1104
|
+
`echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > "$sudoers"`,
|
|
1105
|
+
'visudo -cf "$sudoers" > /dev/null',
|
|
1106
|
+
'install -m 0440 "$sudoers" /etc/sudoers.d/sixb',
|
|
1107
|
+
'rm -f "$sudoers"',
|
|
1108
|
+
'echo "$deploy_user may run sudo systemctl reload caddy, and nothing else"',
|
|
1109
|
+
"",
|
|
1110
|
+
'step "Caddy routes"',
|
|
1111
|
+
"caddyfile=/etc/caddy/Caddyfile",
|
|
1112
|
+
"backup=/etc/caddy/Caddyfile.before-sixb-deploy",
|
|
1113
|
+
"install -d -m 0755 /etc/caddy/sixb.d",
|
|
1114
|
+
'install -d -m 0755 -o "$deploy_user" -g "$deploy_user" "/etc/caddy/sixb.d/$deploy_user"',
|
|
1115
|
+
`printf 'import /etc/caddy/sixb.d/%s/*.caddy\\n' "$deploy_user" > "/etc/caddy/sixb.d/$deploy_user.caddy"`,
|
|
1116
|
+
"restart_caddy=0",
|
|
1117
|
+
`if [ ! -s "$caddyfile" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} "$caddyfile"; then`,
|
|
1118
|
+
' if [ -f "$caddyfile" ]; then cp "$caddyfile" "$backup"; fi',
|
|
1119
|
+
` cat > "$caddyfile" <<'__SIXB_CADDYFILE__'`,
|
|
1120
|
+
"# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.",
|
|
1121
|
+
"{",
|
|
1122
|
+
"\t# Only root and Caddy may change the running configuration.",
|
|
1123
|
+
"\tadmin unix//var/lib/caddy/admin.sock",
|
|
1124
|
+
"}",
|
|
1125
|
+
"",
|
|
1126
|
+
"import /etc/caddy/sixb.d/*.caddy",
|
|
1127
|
+
"__SIXB_CADDYFILE__",
|
|
1128
|
+
" restart_caddy=1",
|
|
1129
|
+
`elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' "$caddyfile"; then`,
|
|
1130
|
+
' cp "$caddyfile" "$backup"',
|
|
1131
|
+
` printf '\\n# Routes written by sixb deploy, one folder per deploy user.\\nimport /etc/caddy/sixb.d/*.caddy\\n' >> "$caddyfile"`,
|
|
1132
|
+
` echo "Kept this server's Caddyfile and added one import; the previous one is $backup."`,
|
|
1133
|
+
"fi",
|
|
1134
|
+
'if ! caddy validate --config "$caddyfile" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',
|
|
1135
|
+
" tail -n 5 /tmp/sixb-caddy-validate.log >&2",
|
|
1136
|
+
' if [ -f "$backup" ]; then cp "$backup" "$caddyfile"; fi',
|
|
1137
|
+
' echo "Caddy rejected the configuration; the previous one is back in place." >&2',
|
|
1138
|
+
" exit 1",
|
|
1139
|
+
"fi",
|
|
1140
|
+
'if [ "$restart_caddy" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',
|
|
1141
|
+
'echo "/etc/caddy/sixb.d/$deploy_user"',
|
|
1142
|
+
"",
|
|
1143
|
+
'step "Checks"',
|
|
1144
|
+
"sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&",
|
|
1145
|
+
' echo "Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config." || true',
|
|
1146
|
+
"sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&",
|
|
1147
|
+
' echo "Warning: root can log in with a password. Set PermitRootLogin prohibit-password." || true',
|
|
1148
|
+
"if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then",
|
|
1149
|
+
" for port in 80 443; do",
|
|
1150
|
+
' ufw status | grep -qE "^$port(/tcp)?\\s+ALLOW" ||',
|
|
1151
|
+
' echo "Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp"',
|
|
1152
|
+
" done",
|
|
1153
|
+
"fi",
|
|
1154
|
+
'echo "Done."'
|
|
1155
|
+
].join(`
|
|
1156
|
+
`);
|
|
1157
|
+
}
|
|
1158
|
+
async function pickPublicKey(input) {
|
|
1159
|
+
if (input.key) {
|
|
1160
|
+
const path = input.key.endsWith(".pub") ? input.key : `${input.key}.pub`;
|
|
1161
|
+
return { text: (await Bun.file(path).text()).trim(), source: path };
|
|
1162
|
+
}
|
|
1163
|
+
for (const identity of input.identityFiles) {
|
|
1164
|
+
const path = `${identity}.pub`;
|
|
1165
|
+
if (await access(path).then(() => true, () => false)) {
|
|
1166
|
+
return { text: (await Bun.file(path).text()).trim(), source: path };
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
const agent = Bun.spawn(["ssh-add", "-L"], { stdout: "pipe", stderr: "ignore" });
|
|
1170
|
+
const first = (await new Response(agent.stdout).text()).split(`
|
|
1171
|
+
`).find((line) => line.trim());
|
|
1172
|
+
if (await agent.exited === 0 && first)
|
|
1173
|
+
return { text: first.trim(), source: "your SSH agent" };
|
|
1174
|
+
throw new Error("[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`.");
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// src/ssh-config.ts
|
|
1178
|
+
import { homedir } from "os";
|
|
1179
|
+
async function resolveSshConfig(destination) {
|
|
1180
|
+
const child = Bun.spawn(["ssh", "-G", destination], { stdout: "pipe", stderr: "pipe" });
|
|
1181
|
+
const [exitCode, output] = await Promise.all([child.exited, new Response(child.stdout).text()]);
|
|
1182
|
+
if (exitCode !== 0)
|
|
1183
|
+
throw new Error(`[SshTarget] ssh -G ${destination} failed.`);
|
|
1184
|
+
let hostname = destination.split("@").at(-1) ?? destination;
|
|
1185
|
+
let port = 22;
|
|
1186
|
+
let proxyJump;
|
|
1187
|
+
const identityFiles = [];
|
|
1188
|
+
for (const line of output.split(`
|
|
1189
|
+
`)) {
|
|
1190
|
+
const [key, ...rest] = line.split(" ");
|
|
1191
|
+
const value = rest.join(" ");
|
|
1192
|
+
if (key === "hostname" && value)
|
|
1193
|
+
hostname = value;
|
|
1194
|
+
if (key === "port" && Number(value) > 0)
|
|
1195
|
+
port = Number(value);
|
|
1196
|
+
if ((key === "proxyjump" || key === "proxycommand") && value && value !== "none") {
|
|
1197
|
+
proxyJump = value;
|
|
1198
|
+
}
|
|
1199
|
+
if (key === "identityfile" && value)
|
|
1200
|
+
identityFiles.push(value.replace(/^~(?=\/)/, homedir()));
|
|
1201
|
+
}
|
|
1202
|
+
return { hostname, port, identityFiles, ...proxyJump ? { proxyJump } : {} };
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// src/ssh-target.ts
|
|
1206
|
+
var OPTIONS = ["host", "user", "ports"];
|
|
1207
|
+
var DEFAULT_USER = "sixb";
|
|
1208
|
+
var DEFAULT_PORTS = {
|
|
1209
|
+
atlas: 3000,
|
|
1210
|
+
app: 3001,
|
|
1211
|
+
api: 3002
|
|
1212
|
+
};
|
|
1213
|
+
var LISTEN_HOST = "127.0.0.1";
|
|
1214
|
+
var USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/;
|
|
1215
|
+
|
|
1216
|
+
class SshTarget {
|
|
1217
|
+
kind = "ssh";
|
|
1218
|
+
host;
|
|
1219
|
+
user;
|
|
1220
|
+
location;
|
|
1221
|
+
#ports;
|
|
1222
|
+
constructor(options) {
|
|
1223
|
+
if (typeof options !== "object" || options === null) {
|
|
1224
|
+
throw new Error('[SshTarget] Pass options, such as `new SshTarget({ host: "203.0.113.10" })`.');
|
|
1225
|
+
}
|
|
1226
|
+
for (const key of Object.keys(options)) {
|
|
1227
|
+
if (!OPTIONS.includes(key)) {
|
|
1228
|
+
throw new Error(`[SshTarget] Unknown option '${key}'. Available: ${OPTIONS.join(", ")}.`);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
this.host = validateHost(options.host);
|
|
1232
|
+
this.user = validateUser(options.user ?? DEFAULT_USER);
|
|
1233
|
+
this.location = `${this.user}@${this.host}`;
|
|
1234
|
+
this.#ports = { ...DEFAULT_PORTS, ...validatePorts(options.ports) };
|
|
1235
|
+
}
|
|
1236
|
+
listenAddress(service) {
|
|
1237
|
+
return { host: LISTEN_HOST, port: this.#ports[service] };
|
|
1238
|
+
}
|
|
1239
|
+
deploy(release, source, context) {
|
|
1240
|
+
return this.#connected((shell) => deployRelease(shell, this.user, release, source, context));
|
|
1241
|
+
}
|
|
1242
|
+
status(context) {
|
|
1243
|
+
return this.#connected((shell) => readStatus(shell, context.name));
|
|
1244
|
+
}
|
|
1245
|
+
logs(options, context) {
|
|
1246
|
+
const terminal = options.follow && Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
1247
|
+
return this.#connected((shell) => streamLogs(shell, context.name, { ...options, terminal }));
|
|
1248
|
+
}
|
|
1249
|
+
control(action, service, context) {
|
|
1250
|
+
return this.#connected((shell) => controlServices(shell, context.name, action, service));
|
|
1251
|
+
}
|
|
1252
|
+
async check(release, context) {
|
|
1253
|
+
const { hostname } = await resolveSshConfig(this.location);
|
|
1254
|
+
const dns = checkDns(release, hostname);
|
|
1255
|
+
let server;
|
|
1256
|
+
try {
|
|
1257
|
+
server = await this.#connected(async (shell) => [
|
|
1258
|
+
{ id: "ssh", label: "SSH", status: "ok", detail: this.location },
|
|
1259
|
+
...await runChecks(shell, {
|
|
1260
|
+
name: context.name,
|
|
1261
|
+
projectPath: context.projectPath,
|
|
1262
|
+
ports: release.services.flatMap((service) => service.http ? [{ service: service.name, port: service.http.port }] : []),
|
|
1263
|
+
location: this.location
|
|
1264
|
+
})
|
|
1265
|
+
]);
|
|
1266
|
+
} catch (error) {
|
|
1267
|
+
server = [sshCheck(this.location, error)];
|
|
1268
|
+
}
|
|
1269
|
+
return [...server, ...await dns];
|
|
1270
|
+
}
|
|
1271
|
+
async setup(release, context) {
|
|
1272
|
+
const before = await this.check(release, context);
|
|
1273
|
+
const serverFixes = before.filter((check) => check.status === "fixable" && check.id !== "project.env" || check.id === "ssh" && check.status !== "ok");
|
|
1274
|
+
const unreachable = before.find((check) => check.id === "ssh" && check.status === "manual");
|
|
1275
|
+
if (unreachable) {
|
|
1276
|
+
throw new Error(`[SshTarget] ${unreachable.detail}`);
|
|
1277
|
+
}
|
|
1278
|
+
if (serverFixes.length > 0) {
|
|
1279
|
+
const admin = context.admin ?? "root";
|
|
1280
|
+
const { identityFiles } = await resolveSshConfig(this.location);
|
|
1281
|
+
const key = await pickPublicKey({ key: context.key, identityFiles });
|
|
1282
|
+
context.write(`Setting up ${this.host} as ${admin}, authorizing ${key.source} for ${this.user}.`);
|
|
1283
|
+
await runAsAdmin(`${admin}@${this.host}`, admin === "root", renderAdminScript({ user: this.user, publicKey: key.text, admin }));
|
|
1284
|
+
}
|
|
1285
|
+
context.write(`Preparing ${context.name} as ${this.user}.`);
|
|
1286
|
+
await this.#connected((shell) => shell.run([
|
|
1287
|
+
`project="$HOME"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,
|
|
1288
|
+
'mkdir -p "$project"',
|
|
1289
|
+
'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi'
|
|
1290
|
+
].join(`
|
|
1291
|
+
`)));
|
|
1292
|
+
}
|
|
1293
|
+
access = {
|
|
1294
|
+
list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),
|
|
1295
|
+
add: (key) => this.#connected((shell) => addKey(shell, key)).then(withoutLine),
|
|
1296
|
+
remove: (match) => this.#connected(async (shell) => (await removeKeys(shell, match)).map(withoutLine))
|
|
1297
|
+
};
|
|
1298
|
+
ci = {
|
|
1299
|
+
create: (job, context) => this.#createCiKey(job, context.name)
|
|
1300
|
+
};
|
|
1301
|
+
async#createCiKey(job, name) {
|
|
1302
|
+
const ssh = await resolveSshConfig(this.location);
|
|
1303
|
+
if (ssh.proxyJump) {
|
|
1304
|
+
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.");
|
|
1305
|
+
}
|
|
1306
|
+
const comment = `sixb-ci:${name}@${job}`;
|
|
1307
|
+
const pair = await generateCiKey(comment);
|
|
1308
|
+
const { key, hostKeys } = await this.#connected(async (shell) => ({
|
|
1309
|
+
hostKeys: await readHostKeys(shell),
|
|
1310
|
+
key: await addKey(shell, pair.publicKey, "restrict")
|
|
1311
|
+
}));
|
|
1312
|
+
return {
|
|
1313
|
+
description: `${key.fingerprint} for ${this.location}, restricted to running commands`,
|
|
1314
|
+
secrets: {
|
|
1315
|
+
SIXB_DEPLOY_SSH_KEY: pair.privateKey,
|
|
1316
|
+
SIXB_DEPLOY_KNOWN_HOSTS: knownHostsLines(hostKeys, ssh.hostname, ssh.port).join(`
|
|
1317
|
+
`)
|
|
1318
|
+
},
|
|
1319
|
+
install: renderCiInstall({ host: this.host, hostname: ssh.hostname, port: ssh.port }),
|
|
1320
|
+
retireOthers: () => this.#connected(async (shell) => (await removeKeysWhere(shell, (other) => other.comment === comment && other.fingerprint !== key.fingerprint)).map(withoutLine)),
|
|
1321
|
+
revoke: () => this.#connected(async (shell) => {
|
|
1322
|
+
await removeKeysWhere(shell, (other) => other.fingerprint === key.fingerprint);
|
|
1323
|
+
})
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
async#connected(work) {
|
|
1327
|
+
const shell = await SshShell.open(this.location);
|
|
1328
|
+
try {
|
|
1329
|
+
return await work(shell);
|
|
1330
|
+
} finally {
|
|
1331
|
+
await shell.close();
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
function validateHost(value) {
|
|
1336
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
1337
|
+
throw new Error("[SshTarget] host must be the server's hostname or IP address.");
|
|
1338
|
+
}
|
|
1339
|
+
const host = value.trim();
|
|
1340
|
+
if (host.includes("@")) {
|
|
1341
|
+
throw new Error(`[SshTarget] host '${host}' includes a user. Set the host alone, and the user with \`user\`.`);
|
|
1342
|
+
}
|
|
1343
|
+
if (host.startsWith("-") || /[\s/\\]/.test(host)) {
|
|
1344
|
+
throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`);
|
|
1345
|
+
}
|
|
1346
|
+
if (host.includes(":") && !isIPv6(host)) {
|
|
1347
|
+
throw new Error(`[SshTarget] host '${host}' includes a port. For an SSH port other than 22, add a Host ` + "entry with that Port to your SSH config and use its name as the host.");
|
|
1348
|
+
}
|
|
1349
|
+
return host;
|
|
1350
|
+
}
|
|
1351
|
+
function validateUser(value) {
|
|
1352
|
+
if (value === "root") {
|
|
1353
|
+
throw new Error("[SshTarget] Deployments never run as root. Use a deploy user without sudo, such as the " + 'default "sixb".');
|
|
1354
|
+
}
|
|
1355
|
+
if (typeof value !== "string" || !USER_PATTERN.test(value)) {
|
|
1356
|
+
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.");
|
|
1357
|
+
}
|
|
1358
|
+
return value;
|
|
1359
|
+
}
|
|
1360
|
+
function validatePorts(value) {
|
|
1361
|
+
if (value === undefined)
|
|
1362
|
+
return {};
|
|
1363
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1364
|
+
throw new Error("[SshTarget] ports must be an object, such as `{ api: 3012 }`.");
|
|
1365
|
+
}
|
|
1366
|
+
const ports = {};
|
|
1367
|
+
for (const [service, port] of Object.entries(value)) {
|
|
1368
|
+
if (!Object.hasOwn(DEFAULT_PORTS, service)) {
|
|
1369
|
+
throw new Error(`[SshTarget] ports.${service} is not an HTTP service. Available: api, atlas, app.`);
|
|
1370
|
+
}
|
|
1371
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
|
|
1372
|
+
throw new Error(`[SshTarget] ports.${service} must be a port from 1024 to 65535.`);
|
|
1373
|
+
}
|
|
1374
|
+
ports[service] = port;
|
|
1375
|
+
}
|
|
1376
|
+
return ports;
|
|
1377
|
+
}
|
|
1378
|
+
function sshCheck(location, error) {
|
|
1379
|
+
const message = (error instanceof Error ? error.message : String(error)).split(`
|
|
1380
|
+
`)[0]?.replace(/^\[SshTarget\] /, "") ?? "";
|
|
1381
|
+
if (error instanceof RemoteScriptError && /refused your SSH key/.test(message)) {
|
|
1382
|
+
return {
|
|
1383
|
+
id: "ssh",
|
|
1384
|
+
label: "SSH",
|
|
1385
|
+
status: "fixable",
|
|
1386
|
+
detail: message,
|
|
1387
|
+
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.`
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
return {
|
|
1391
|
+
id: "ssh",
|
|
1392
|
+
label: "SSH",
|
|
1393
|
+
status: "manual",
|
|
1394
|
+
detail: message || `Cannot reach ${location}.`
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
function withoutLine({ type, fingerprint, comment, restricted }) {
|
|
1398
|
+
return { type, fingerprint, comment, restricted };
|
|
1399
|
+
}
|
|
1400
|
+
async function runAsAdmin(destination, root, script) {
|
|
1401
|
+
const command = `${root ? "" : "sudo "}bash -c ${shellQuote(script)}`;
|
|
1402
|
+
const ssh = ["ssh", "-tt", "-o", "ConnectTimeout=15", "-o", "LogLevel=ERROR"];
|
|
1403
|
+
const child = Bun.spawn([...ssh, destination, command], {
|
|
1404
|
+
stdio: ["inherit", "inherit", "inherit"]
|
|
1405
|
+
});
|
|
1406
|
+
const exitCode = await child.exited;
|
|
1407
|
+
if (exitCode !== 0) {
|
|
1408
|
+
throw new Error(`[SshTarget] Setting up the server as ${destination} failed (exit code ${exitCode}).`);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
export {
|
|
1412
|
+
SshTarget
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
//# debugId=13993CAB928AAB0064756E2164756E21
|