@sixb/deploy-ssh 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +51 -42
  2. package/dist/check/index.d.ts +24 -0
  3. package/dist/check/index.d.ts.map +1 -0
  4. package/dist/check/judge.d.ts +23 -0
  5. package/dist/check/judge.d.ts.map +1 -0
  6. package/dist/index.js +599 -1102
  7. package/dist/index.js.map +10 -15
  8. package/dist/layout.d.ts +91 -18
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -2
  11. package/dist/operations.d.ts.map +1 -1
  12. package/dist/plan.d.ts +25 -0
  13. package/dist/plan.d.ts.map +1 -0
  14. package/dist/render.d.ts +20 -10
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +15 -3
  17. package/dist/server/manifest.d.ts.map +1 -1
  18. package/dist/server/release-host.d.ts +4 -0
  19. package/dist/server/release-host.d.ts.map +1 -0
  20. package/dist/server/release.d.ts +46 -0
  21. package/dist/server/release.d.ts.map +1 -0
  22. package/dist/server/state.d.ts +2 -0
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +12 -4
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -18
  27. package/dist/ssh-target.d.ts.map +1 -1
  28. package/dist/transport.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/bootstrap.sh +93 -0
  31. package/src/check/index.ts +117 -0
  32. package/src/check/judge.ts +299 -0
  33. package/src/check/probe.sh +99 -0
  34. package/src/layout.ts +117 -34
  35. package/src/operations.ts +104 -61
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +128 -31
  38. package/src/server/cli.ts +26 -9
  39. package/src/server/manifest.ts +42 -4
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +3 -1
  43. package/src/server/supervisor.ts +127 -55
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +46 -227
  46. package/src/transport.ts +28 -12
  47. package/dist/access.d.ts +0 -11
  48. package/dist/access.d.ts.map +0 -1
  49. package/dist/check.d.ts +0 -31
  50. package/dist/check.d.ts.map +0 -1
  51. package/dist/ci.d.ts +0 -27
  52. package/dist/ci.d.ts.map +0 -1
  53. package/dist/keys.d.ts +0 -13
  54. package/dist/keys.d.ts.map +0 -1
  55. package/dist/scripts.d.ts +0 -38
  56. package/dist/scripts.d.ts.map +0 -1
  57. package/dist/setup.d.ts +0 -32
  58. package/dist/setup.d.ts.map +0 -1
  59. package/src/access.ts +0 -107
  60. package/src/check.ts +0 -231
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -323
  64. package/src/setup.ts +0 -203
package/src/scripts.ts DELETED
@@ -1,323 +0,0 @@
1
- import type { DeployCommand, DeployRecord, DeployRelease } from "@sixb/core/deploy"
2
- import type { DeploymentLayout } from "./layout"
3
- import { renderCaddySnippet, renderCtl, renderProcessManifest, renderUnit } from "./render"
4
- import { shellQuote, writeFileCommand } from "./shell"
5
-
6
- /** A line the deploy script prints around each step; the target turns it into progress. */
7
- export const STEP_MARKER = "__SIXB_STEP__"
8
-
9
- /** The server's home directory, and a fresh directory to upload the source into. */
10
- export function renderPrepareScript(name: string, commit: string): string {
11
- return [
12
- `root="$HOME"/${shellQuote(name)}`,
13
- 'mkdir -p "$root/deploy/incoming"',
14
- `incoming="$(mktemp -d "$root/deploy/incoming/${commit.slice(0, 12)}.XXXXXX")"`,
15
- // `mktemp` makes it 0700, and GNU tar passes the mode of the upload's `.` on to `code/`, which
16
- // would lock out the admin, who reads the code through the deploy user's group.
17
- 'chmod 755 "$incoming"',
18
- `printf '%s\\n%s\\n' "$HOME" "$incoming"`,
19
- ].join("\n")
20
- }
21
-
22
- /** Extracts one uploaded archive from standard input. */
23
- export function renderReceiveScript(incoming: string, path: string): string {
24
- const directory = path === "." ? incoming : `${incoming}/${path}`
25
- return `mkdir -p ${shellQuote(directory)} && tar -x -f - -C ${shellQuote(directory)}`
26
- }
27
-
28
- export interface DeployScriptInput {
29
- readonly release: DeployRelease
30
- readonly layout: DeploymentLayout
31
- readonly incoming: string
32
- readonly record: DeployRecord
33
- }
34
-
35
- export interface DeployScript {
36
- readonly labels: readonly string[]
37
- readonly script: string
38
- }
39
-
40
- interface Step {
41
- readonly label: string
42
- readonly body: string
43
- }
44
-
45
- /**
46
- * Everything the server does once the source is uploaded, as one script that holds the
47
- * deployment's lock throughout. It runs with standard input closed: bash reads the whole `main`
48
- * function before running any of it, so no command can swallow the rest of the script.
49
- */
50
- export function renderDeployScript(input: DeployScriptInput): DeployScript {
51
- const { release, layout } = input
52
- const api = release.services.find((service) => service.http?.readinessPath)
53
- const steps: Step[] = [
54
- { label: "Apply files", body: renderApplyFiles(layout, input.incoming) },
55
- { label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },
56
- { label: "Install dependencies", body: renderInstallDependencies() },
57
- ...(release.steps.env ? [envStep(release.steps.env, layout)] : []),
58
- ...release.steps.build.map((command) => runStep(command)),
59
- // Everything that can be rejected happens while the previous release still serves: services
60
- // are down only from here to "Start services".
61
- { label: "Write services", body: renderWriteServices(release, layout) },
62
- { label: "Update routes", body: renderUpdateRoutes(release, layout) },
63
- { label: "Stop services", body: renderStopServices() },
64
- ...release.steps.beforeStart.map((command) => runStep(command)),
65
- { label: "Start services", body: renderStartServices() },
66
- {
67
- label: "Check services",
68
- body: renderCheckServices(
69
- api?.http ? `http://${api.http.host}:${api.http.port}${api.http.readinessPath}` : null
70
- ),
71
- },
72
- {
73
- label: "Record release",
74
- body: writeFileCommand(layout.releaseRecord, `${JSON.stringify(input.record)}\n`),
75
- },
76
- ]
77
-
78
- const script = [
79
- "set -euo pipefail",
80
- "main() {",
81
- renderEnvironment(release, layout),
82
- renderTakeLock(layout),
83
- ...steps.flatMap((step, index) => [
84
- `printf '\\n%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} start`,
85
- step.body,
86
- `printf '%s\\t%s\\t%s\\n' ${STEP_MARKER} ${index} done`,
87
- ]),
88
- "}",
89
- "main </dev/null",
90
- "",
91
- ].join("\n")
92
-
93
- return { labels: steps.map((step) => step.label), script }
94
- }
95
-
96
- function renderEnvironment(release: DeployRelease, layout: DeploymentLayout): string {
97
- const variables: Record<string, string> = {
98
- ROOT: layout.root,
99
- CODE: layout.code,
100
- PROJECT: layout.project,
101
- DEPLOY: layout.deployDir,
102
- BUN: layout.bun,
103
- BUN_DIR: layout.bunDir,
104
- BUN_VERSION: release.bunVersion,
105
- CTL: layout.ctl,
106
- UNIT: layout.unitName,
107
- UNIT_PATH: layout.unit,
108
- CADDY_DIR: layout.caddyDir,
109
- CADDY_SNIPPET: layout.caddySnippet,
110
- }
111
- return [
112
- ...Object.entries(variables).map(([name, value]) => `${name}=${shellQuote(value)}`),
113
- // The steps run with the release's environment; the project's `.env` fills in the rest.
114
- ...Object.entries(release.env).map(([name, value]) => `export ${name}=${shellQuote(value)}`),
115
- 'export PATH="$BUN_DIR:$PATH"',
116
- // `systemctl --user` finds the user's systemd through this; SSH sessions usually set it.
117
- 'printenv XDG_RUNTIME_DIR > /dev/null || export XDG_RUNTIME_DIR="/run/user/$(id -u)"',
118
- ].join("\n")
119
- }
120
-
121
- function renderTakeLock(layout: DeploymentLayout): string {
122
- return [
123
- `exec 9>${shellQuote(layout.lock)}`,
124
- "if ! flock -n 9; then",
125
- ' echo "Waiting for another deploy or script run of this project to finish…"',
126
- "fi",
127
- "if ! flock -w 600 9; then",
128
- ' echo "Another deploy or script run of this project has held its lock for 10 minutes." >&2',
129
- " exit 1",
130
- "fi",
131
- ].join("\n")
132
- }
133
-
134
- /**
135
- * Makes `code/` match the commit the way `git reset --hard` would: committed files replace what is
136
- * there, files the previous deploy brought and this one does not are removed, and everything else
137
- * — `.env`, `.sixb/`, `node_modules/` — stays. A committed `.env` is never copied over the
138
- * server's.
139
- */
140
- export function renderApplyFiles(layout: DeploymentLayout, incoming: string): string {
141
- return [
142
- `incoming=${shellQuote(incoming)}`,
143
- `files=${shellQuote(layout.fileList)}`,
144
- `code=${shellQuote(layout.code)}`,
145
- 'listed="$incoming.files"',
146
- '(cd "$incoming" && find . \\( -type f -o -type l \\) ! -name .env | LC_ALL=C sort) > "$listed"',
147
- 'mkdir -p "$code"',
148
- 'if [ -f "$files" ]; then',
149
- ' LC_ALL=C comm -23 "$files" "$listed" | while IFS= read -r path; do',
150
- ' rm -f "$code/$path"',
151
- ' dir="$(dirname "$code/$path")"',
152
- ' while [ "$dir" != "$code" ] && [ "$dir" != "$code/." ] && rmdir "$dir" 2>/dev/null; do',
153
- ' dir="$(dirname "$dir")"',
154
- " done",
155
- " done",
156
- "fi",
157
- `(cd "$incoming" && tar -c -f - --exclude=.env .) | (cd "$code" && tar -x -f -)`,
158
- 'mv "$listed" "$files"',
159
- 'rm -rf "$incoming"',
160
- // Uploads a deploy abandoned before it took the lock.
161
- 'find "$(dirname "$incoming")" -mindepth 1 -maxdepth 1 -mmin +1440 -exec rm -rf {} + 2>/dev/null || true',
162
- ].join("\n")
163
- }
164
-
165
- /** Downloads the pinned Bun once per user and version, checking it against the release's sums. */
166
- function renderInstallBun(version: string): string {
167
- const release = `https://github.com/oven-sh/bun/releases/download/bun-v${version}`
168
- return [
169
- 'if [ ! -x "$BUN" ]; then',
170
- ' case "$(uname -m)" in',
171
- " x86_64 | amd64) arch=x64 ;;",
172
- " aarch64 | arm64) arch=aarch64 ;;",
173
- ' *) echo "Bun has no Linux build for $(uname -m)." >&2; exit 1 ;;',
174
- " esac",
175
- // Bun's default x64 build needs AVX2; older CPUs take the baseline build.
176
- ' if [ "$arch" = x64 ] && ! grep -q avx2 /proc/cpuinfo; then arch=x64-baseline; fi',
177
- ' asset="bun-linux-$arch"',
178
- ' download="$(mktemp -d)"',
179
- ` curl -fsSL --retry 3 -o "$download/$asset.zip" ${shellQuote(release)}"/$asset.zip"`,
180
- ` curl -fsSL --retry 3 -o "$download/SHASUMS256.txt" ${shellQuote(release)}/SHASUMS256.txt`,
181
- ' (cd "$download" && grep " $asset.zip\\$" SHASUMS256.txt | sha256sum -c --quiet -)',
182
- ' unzip -q "$download/$asset.zip" -d "$download"',
183
- ' mkdir -p "$BUN_DIR"',
184
- ' mv "$download/$asset/bun" "$BUN"',
185
- ' rm -rf "$download"',
186
- "fi",
187
- // Dependency lifecycle scripts call `node`; with none installed, Bun runs them.
188
- 'command -v node > /dev/null || ln -s "$BUN" "$BUN_DIR/node"',
189
- '"$BUN" --version',
190
- ].join("\n")
191
- }
192
-
193
- function renderInstallDependencies(): string {
194
- return [
195
- 'cd "$PROJECT"',
196
- '"$BUN" install --frozen-lockfile',
197
- "for bin in sixb sixb-deploy-ssh; do",
198
- ' if [ ! -e "$PROJECT/node_modules/.bin/$bin" ]; then',
199
- ' package="@sixb/cli"; [ "$bin" = sixb ] || package="@sixb/deploy-ssh"',
200
- ' echo "$package is not installed. Add it to the project dependencies." >&2',
201
- " exit 1",
202
- " fi",
203
- "done",
204
- ].join("\n")
205
- }
206
-
207
- function runStep(command: DeployCommand): Step {
208
- const program = command.program === "sixb" ? '"$PROJECT/node_modules/.bin/sixb"' : ""
209
- return {
210
- label: [command.program, ...command.args].join(" "),
211
- body: [
212
- 'cd "$PROJECT"',
213
- `"$BUN" ${program} ${command.args.map(shellQuote).join(" ")}`.replace(/ {2,}/g, " "),
214
- ].join("\n"),
215
- }
216
- }
217
-
218
- /** Pulls `.env` with the token only this step reads, so no build or service ever holds it. */
219
- function envStep(command: DeployCommand, layout: DeploymentLayout): Step {
220
- const step = runStep(command)
221
- return { ...step, body: `${step.body} --token-file ${shellQuote(layout.envToken)}` }
222
- }
223
-
224
- function renderStopServices(): string {
225
- return [
226
- 'if systemctl --user is-active --quiet "$UNIT"; then',
227
- ' systemctl --user stop "$UNIT"',
228
- "else",
229
- " echo 'Services were not running.'",
230
- "fi",
231
- ].join("\n")
232
- }
233
-
234
- function renderWriteServices(release: DeployRelease, layout: DeploymentLayout): string {
235
- return [
236
- writeFileCommand(
237
- layout.manifest,
238
- `${JSON.stringify(renderProcessManifest(release, layout), null, 2)}\n`
239
- ),
240
- writeFileCommand(layout.ctl, renderCtl(layout)),
241
- 'chmod 755 "$CTL"',
242
- 'mkdir -p "$(dirname "$UNIT_PATH")"',
243
- writeFileCommand(`${layout.unit}.new`, renderUnit(release, layout)),
244
- 'if cmp -s "$UNIT_PATH.new" "$UNIT_PATH"; then',
245
- ' rm -f "$UNIT_PATH.new"',
246
- "else",
247
- ' mv "$UNIT_PATH.new" "$UNIT_PATH"',
248
- " systemctl --user daemon-reload",
249
- ' systemctl --user enable "$UNIT"',
250
- "fi",
251
- ].join("\n")
252
- }
253
-
254
- /**
255
- * Installs the deployment's Caddy routes when they changed. Caddy has to accept the whole
256
- * configuration before it reloads; otherwise the previous routes come back and the deploy stops.
257
- */
258
- function renderUpdateRoutes(release: DeployRelease, layout: DeploymentLayout): string {
259
- return [
260
- `new=${shellQuote(`${layout.deployDir}/Caddyfile`)}`,
261
- writeFileCommand(`${layout.deployDir}/Caddyfile`, renderCaddySnippet(release)),
262
- 'if cmp -s "$new" "$CADDY_SNIPPET"; then',
263
- " echo 'Routes unchanged.'",
264
- "else",
265
- ' if [ ! -w "$CADDY_DIR" ]; then',
266
- ' echo "$CADDY_DIR is missing or not writable, so this server is not set up for sixb deploy." >&2',
267
- " exit 1",
268
- " fi",
269
- ' previous="$DEPLOY/Caddyfile.previous"',
270
- ' rm -f "$previous"',
271
- ' if [ -f "$CADDY_SNIPPET" ]; then cp "$CADDY_SNIPPET" "$previous"; fi',
272
- ' cp "$new" "$CADDY_SNIPPET"',
273
- ' if ! caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile > "$DEPLOY/caddy-validate.log" 2>&1; then',
274
- ' if [ -f "$previous" ]; then cp "$previous" "$CADDY_SNIPPET"; else rm -f "$CADDY_SNIPPET"; fi',
275
- ' tail -n 20 "$DEPLOY/caddy-validate.log" >&2',
276
- " echo 'Caddy rejected the routes; the previous ones are back in place.' >&2",
277
- " exit 1",
278
- " fi",
279
- " sudo -n /usr/bin/systemctl reload caddy",
280
- "fi",
281
- ].join("\n")
282
- }
283
-
284
- function renderStartServices(): string {
285
- return [
286
- 'systemctl --user restart "$UNIT"',
287
- 'systemctl --user is-active --quiet "$UNIT"',
288
- // Where "Check services" counts its quiet window from.
289
- "started=$SECONDS",
290
- ].join("\n")
291
- }
292
-
293
- /**
294
- * Done means healthy, not just started: the API answers its readiness route, and no process has
295
- * exited in its first seconds. Those seconds count from "Start services", so the time the API
296
- * takes to boot is part of them rather than added to them.
297
- */
298
- export function renderCheckServices(readinessUrl: string | null): string {
299
- const waitForApi = readinessUrl
300
- ? [
301
- `ready_url=${shellQuote(readinessUrl)}`,
302
- "ready=0",
303
- "for attempt in $(seq 1 90); do",
304
- ` if "$BUN" -e 'const r = await fetch(process.argv[1]).catch(() => null); process.exit(r?.ok ? 0 : 1)' "$ready_url" 2>/dev/null; then`,
305
- " ready=1",
306
- " break",
307
- " fi",
308
- " sleep 1",
309
- "done",
310
- 'if [ "$ready" != 1 ]; then',
311
- ' echo "The API did not answer $ready_url within 90 seconds. Its latest log lines:" >&2',
312
- ' "$CTL" logs api --tail 30 >&2 || true',
313
- " exit 1",
314
- "fi",
315
- ]
316
- : []
317
- return [
318
- ...waitForApi,
319
- "quiet=$((5 - (SECONDS - started)))",
320
- 'if [ "$quiet" -gt 0 ]; then sleep "$quiet"; fi',
321
- '"$CTL" status --check',
322
- ].join("\n")
323
- }
package/src/setup.ts DELETED
@@ -1,203 +0,0 @@
1
- import { access } from "node:fs/promises"
2
- import { ENV_TOKEN_FILE } from "./layout"
3
- import { shellQuote } from "./shell"
4
- import { RemoteScriptError, type RemoteShell } from "./transport"
5
-
6
- /** The first line of the Caddyfile the Debian and Ubuntu packages install. */
7
- const PACKAGED_CADDYFILE = "The Caddyfile is an easy way to configure your Caddy web server."
8
-
9
- /**
10
- * Everything that needs root, run once per server and once per deploy user, safe to run again.
11
- * Afterwards the deploy user needs no sudo but reloading Caddy.
12
- *
13
- * Caddy's configuration is taken over only when it is still the one the package installed. A
14
- * server that already serves other sites keeps its configuration and gains one import line (the
15
- * old file is kept beside it), and its admin API stays where that configuration puts it.
16
- */
17
- export function renderAdminScript(input: {
18
- readonly user: string
19
- readonly publicKey: string
20
- readonly admin: string
21
- }): string {
22
- const user = shellQuote(input.user)
23
- return [
24
- "set -euo pipefail",
25
- `deploy_user=${user}`,
26
- `public_key=${shellQuote(input.publicKey)}`,
27
- `admin_login=${shellQuote(input.admin)}`,
28
- 'step() { printf "\\n== %s\\n" "$1"; }',
29
- // Shows a command's output only when it fails, so a first setup is not pages of apt.
30
- 'quiet() { log="$(mktemp)"; if "$@" > "$log" 2>&1; then rm -f "$log"; else status=$?; tail -n 20 "$log" >&2; rm -f "$log"; return "$status"; fi; }',
31
- "",
32
- 'step "Server"',
33
- "if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then",
34
- ' echo "sixb deploy needs an Ubuntu or Debian server with systemd." >&2',
35
- " exit 1",
36
- "fi",
37
- '. /etc/os-release && echo "$PRETTY_NAME"',
38
- "",
39
- 'step "Packages"',
40
- "export DEBIAN_FRONTEND=noninteractive",
41
- 'missing=""',
42
- "for package in git curl unzip ca-certificates gnupg; do",
43
- // `ii` is installed; `dpkg -s` also succeeds for a removed package whose config it keeps.
44
- ' dpkg -l "$package" 2> /dev/null | grep -q "^ii" || missing="$missing $package"',
45
- "done",
46
- 'if [ -n "$missing" ]; then',
47
- ' echo "Installing$missing"',
48
- " quiet apt-get update",
49
- " quiet apt-get install -y $missing",
50
- "fi",
51
- "if ! command -v caddy > /dev/null; then",
52
- ' echo "Installing caddy"',
53
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |",
54
- " gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
55
- " curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
56
- " quiet apt-get update",
57
- " quiet apt-get install -y caddy",
58
- "fi",
59
- "echo \"git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)\"",
60
- "",
61
- 'step "Deploy user $deploy_user"',
62
- 'id "$deploy_user" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group "$deploy_user"',
63
- 'home="$(getent passwd "$deploy_user" | cut -d: -f6)"',
64
- 'chmod 750 "$home"',
65
- 'install -d -m 0700 -o "$deploy_user" -g "$deploy_user" "$home/.ssh"',
66
- 'touch "$home/.ssh/authorized_keys"',
67
- 'grep -qxF "$public_key" "$home/.ssh/authorized_keys" || echo "$public_key" >> "$home/.ssh/authorized_keys"',
68
- 'chown "$deploy_user:$deploy_user" "$home/.ssh/authorized_keys"',
69
- 'chmod 0600 "$home/.ssh/authorized_keys"',
70
- 'loginctl enable-linger "$deploy_user"',
71
- 'grep -qs XDG_RUNTIME_DIR "$home/.profile" ||',
72
- ' echo \'export XDG_RUNTIME_DIR="/run/user/$(id -u)"\' >> "$home/.profile"',
73
- 'chown "$deploy_user:$deploy_user" "$home/.profile"',
74
- // The admin reads every project under this user without sudo; `.env` stays 0600.
75
- 'if [ "$admin_login" != root ]; then usermod -aG "$deploy_user" "$admin_login"; fi',
76
- 'echo "$home, key-only, services start at boot"',
77
- "",
78
- 'step "Caddy reload"',
79
- "groupadd -f sixb-deploy",
80
- 'usermod -aG sixb-deploy "$deploy_user"',
81
- 'sudoers="$(mktemp)"',
82
- "echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > \"$sudoers\"",
83
- 'visudo -cf "$sudoers" > /dev/null',
84
- 'install -m 0440 "$sudoers" /etc/sudoers.d/sixb',
85
- 'rm -f "$sudoers"',
86
- 'echo "$deploy_user may run sudo systemctl reload caddy, and nothing else"',
87
- "",
88
- 'step "Caddy routes"',
89
- "caddyfile=/etc/caddy/Caddyfile",
90
- "backup=/etc/caddy/Caddyfile.before-sixb-deploy",
91
- "install -d -m 0755 /etc/caddy/sixb.d",
92
- 'install -d -m 0755 -o "$deploy_user" -g "$deploy_user" "/etc/caddy/sixb.d/$deploy_user"',
93
- // Caddy allows one `*` per import pattern, so each deploy user's folder has an index file.
94
- 'printf \'import /etc/caddy/sixb.d/%s/*.caddy\\n\' "$deploy_user" > "/etc/caddy/sixb.d/$deploy_user.caddy"',
95
- "restart_caddy=0",
96
- `if [ ! -s "$caddyfile" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} "$caddyfile"; then`,
97
- ' if [ -f "$caddyfile" ]; then cp "$caddyfile" "$backup"; fi',
98
- " cat > \"$caddyfile\" <<'__SIXB_CADDYFILE__'",
99
- "# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.",
100
- "{",
101
- "\t# Only root and Caddy may change the running configuration.",
102
- "\tadmin unix//var/lib/caddy/admin.sock",
103
- "}",
104
- "",
105
- "import /etc/caddy/sixb.d/*.caddy",
106
- "__SIXB_CADDYFILE__",
107
- // A restart, not a reload: the admin address itself moves.
108
- " restart_caddy=1",
109
- "elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' \"$caddyfile\"; then",
110
- ' cp "$caddyfile" "$backup"',
111
- " printf '\\n# Routes written by sixb deploy, one folder per deploy user.\\nimport /etc/caddy/sixb.d/*.caddy\\n' >> \"$caddyfile\"",
112
- ' echo "Kept this server\'s Caddyfile and added one import; the previous one is $backup."',
113
- "fi",
114
- 'if ! caddy validate --config "$caddyfile" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',
115
- " tail -n 5 /tmp/sixb-caddy-validate.log >&2",
116
- ' if [ -f "$backup" ]; then cp "$backup" "$caddyfile"; fi',
117
- ' echo "Caddy rejected the configuration; the previous one is back in place." >&2',
118
- " exit 1",
119
- "fi",
120
- 'if [ "$restart_caddy" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',
121
- 'echo "/etc/caddy/sixb.d/$deploy_user"',
122
- "",
123
- 'step "Checks"',
124
- // Reported, not changed: editing sshd or the firewall is how people lock themselves out.
125
- "sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&",
126
- ' echo "Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config." || true',
127
- "sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&",
128
- ' echo "Warning: root can log in with a password. Set PermitRootLogin prohibit-password." || true',
129
- "if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then",
130
- " for port in 80 443; do",
131
- ' ufw status | grep -qE "^$port(/tcp)?\\s+ALLOW" ||',
132
- ' echo "Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp"',
133
- " done",
134
- "fi",
135
- 'echo "Done."',
136
- ].join("\n")
137
- }
138
-
139
- /**
140
- * The public key to authorize for deploys: the one given, else the first key SSH would offer to
141
- * the server that has a `.pub` beside it, else the first key in the SSH agent.
142
- */
143
- export async function pickPublicKey(input: {
144
- readonly key?: string
145
- readonly identityFiles: readonly string[]
146
- }): Promise<{ readonly text: string; readonly source: string }> {
147
- if (input.key) {
148
- const path = input.key.endsWith(".pub") ? input.key : `${input.key}.pub`
149
- return { text: (await Bun.file(path).text()).trim(), source: path }
150
- }
151
- for (const identity of input.identityFiles) {
152
- const path = `${identity}.pub`
153
- if (
154
- await access(path).then(
155
- () => true,
156
- () => false
157
- )
158
- ) {
159
- return { text: (await Bun.file(path).text()).trim(), source: path }
160
- }
161
- }
162
- const agent = Bun.spawn(["ssh-add", "-L"], { stdout: "pipe", stderr: "ignore" })
163
- const first = (await new Response(agent.stdout).text()).split("\n").find((line) => line.trim())
164
- if ((await agent.exited) === 0 && first) return { text: first.trim(), source: "your SSH agent" }
165
- throw new Error(
166
- "[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`."
167
- )
168
- }
169
-
170
- /**
171
- * Creates the deploy's token when the server doesn't have one. This asks the server rather than
172
- * going by the checks setup started with: on a fresh server those stop at SSH, before they reach
173
- * the token. Returns whether it installed one.
174
- */
175
- export async function ensureEnvToken(
176
- shell: RemoteShell,
177
- name: string,
178
- createToken: () => Promise<string>
179
- ): Promise<boolean> {
180
- const path = `"$HOME"/${shellQuote(`${name}/${ENV_TOKEN_FILE}`)}`
181
-
182
- const installed = await shell.run(`[ -s ${path} ]`).then(
183
- () => true,
184
- (error: unknown) => {
185
- if (error instanceof RemoteScriptError && error.exitCode === 1) return false
186
- throw error
187
- }
188
- )
189
- if (installed) return false
190
-
191
- // On standard input, because a script is an argument any process on the server can read.
192
- await shell.run(
193
- [
194
- "set -e",
195
- "umask 077",
196
- `mkdir -p "$HOME"/${shellQuote(name)}`,
197
- `cat > ${path}.new`,
198
- `mv ${path}.new ${path}`,
199
- ].join("\n"),
200
- { stdin: new Blob([`${await createToken()}\n`]).stream() }
201
- )
202
- return true
203
- }