@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/src/setup.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { access } from "node:fs/promises"
|
|
2
|
+
import { shellQuote } from "./shell"
|
|
3
|
+
|
|
4
|
+
/** The first line of the Caddyfile the Debian and Ubuntu packages install. */
|
|
5
|
+
const PACKAGED_CADDYFILE = "The Caddyfile is an easy way to configure your Caddy web server."
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Everything that needs root, run once per server and once per deploy user, safe to run again.
|
|
9
|
+
* Afterwards the deploy user needs no sudo but reloading Caddy.
|
|
10
|
+
*
|
|
11
|
+
* Caddy's configuration is taken over only when it is still the one the package installed. A
|
|
12
|
+
* server that already serves other sites keeps its configuration and gains one import line (the
|
|
13
|
+
* old file is kept beside it), and its admin API stays where that configuration puts it.
|
|
14
|
+
*/
|
|
15
|
+
export function renderAdminScript(input: {
|
|
16
|
+
readonly user: string
|
|
17
|
+
readonly publicKey: string
|
|
18
|
+
readonly admin: string
|
|
19
|
+
}): string {
|
|
20
|
+
const user = shellQuote(input.user)
|
|
21
|
+
return [
|
|
22
|
+
"set -euo pipefail",
|
|
23
|
+
`deploy_user=${user}`,
|
|
24
|
+
`public_key=${shellQuote(input.publicKey)}`,
|
|
25
|
+
`admin_login=${shellQuote(input.admin)}`,
|
|
26
|
+
'step() { printf "\\n== %s\\n" "$1"; }',
|
|
27
|
+
// Shows a command's output only when it fails, so a first setup is not pages of apt.
|
|
28
|
+
'quiet() { log="$(mktemp)"; if "$@" > "$log" 2>&1; then rm -f "$log"; else status=$?; tail -n 20 "$log" >&2; rm -f "$log"; return "$status"; fi; }',
|
|
29
|
+
"",
|
|
30
|
+
'step "Server"',
|
|
31
|
+
"if ! command -v apt-get > /dev/null || ! command -v systemctl > /dev/null; then",
|
|
32
|
+
' echo "sixb deploy needs an Ubuntu or Debian server with systemd." >&2',
|
|
33
|
+
" exit 1",
|
|
34
|
+
"fi",
|
|
35
|
+
'. /etc/os-release && echo "$PRETTY_NAME"',
|
|
36
|
+
"",
|
|
37
|
+
'step "Packages"',
|
|
38
|
+
"export DEBIAN_FRONTEND=noninteractive",
|
|
39
|
+
'missing=""',
|
|
40
|
+
"for package in git curl unzip ca-certificates gnupg; do",
|
|
41
|
+
// `ii` is installed; `dpkg -s` also succeeds for a removed package whose config it keeps.
|
|
42
|
+
' dpkg -l "$package" 2> /dev/null | grep -q "^ii" || missing="$missing $package"',
|
|
43
|
+
"done",
|
|
44
|
+
'if [ -n "$missing" ]; then',
|
|
45
|
+
' echo "Installing$missing"',
|
|
46
|
+
" quiet apt-get update",
|
|
47
|
+
" quiet apt-get install -y $missing",
|
|
48
|
+
"fi",
|
|
49
|
+
"if ! command -v caddy > /dev/null; then",
|
|
50
|
+
' echo "Installing caddy"',
|
|
51
|
+
" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/gpg.key |",
|
|
52
|
+
" gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg",
|
|
53
|
+
" curl -fsSL https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt > /etc/apt/sources.list.d/caddy-stable.list",
|
|
54
|
+
" quiet apt-get update",
|
|
55
|
+
" quiet apt-get install -y caddy",
|
|
56
|
+
"fi",
|
|
57
|
+
"echo \"git, curl, unzip, caddy $(caddy version | cut -d' ' -f1)\"",
|
|
58
|
+
"",
|
|
59
|
+
'step "Deploy user $deploy_user"',
|
|
60
|
+
'id "$deploy_user" > /dev/null 2>&1 || useradd --create-home --shell /bin/bash --user-group "$deploy_user"',
|
|
61
|
+
'home="$(getent passwd "$deploy_user" | cut -d: -f6)"',
|
|
62
|
+
'chmod 750 "$home"',
|
|
63
|
+
'install -d -m 0700 -o "$deploy_user" -g "$deploy_user" "$home/.ssh"',
|
|
64
|
+
'touch "$home/.ssh/authorized_keys"',
|
|
65
|
+
'grep -qxF "$public_key" "$home/.ssh/authorized_keys" || echo "$public_key" >> "$home/.ssh/authorized_keys"',
|
|
66
|
+
'chown "$deploy_user:$deploy_user" "$home/.ssh/authorized_keys"',
|
|
67
|
+
'chmod 0600 "$home/.ssh/authorized_keys"',
|
|
68
|
+
'loginctl enable-linger "$deploy_user"',
|
|
69
|
+
'grep -qs XDG_RUNTIME_DIR "$home/.profile" ||',
|
|
70
|
+
' echo \'export XDG_RUNTIME_DIR="/run/user/$(id -u)"\' >> "$home/.profile"',
|
|
71
|
+
'chown "$deploy_user:$deploy_user" "$home/.profile"',
|
|
72
|
+
// The admin reads every project under this user without sudo; `.env` stays 0600.
|
|
73
|
+
'if [ "$admin_login" != root ]; then usermod -aG "$deploy_user" "$admin_login"; fi',
|
|
74
|
+
'echo "$home, key-only, services start at boot"',
|
|
75
|
+
"",
|
|
76
|
+
'step "Caddy reload"',
|
|
77
|
+
"groupadd -f sixb-deploy",
|
|
78
|
+
'usermod -aG sixb-deploy "$deploy_user"',
|
|
79
|
+
'sudoers="$(mktemp)"',
|
|
80
|
+
"echo '%sixb-deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload caddy' > \"$sudoers\"",
|
|
81
|
+
'visudo -cf "$sudoers" > /dev/null',
|
|
82
|
+
'install -m 0440 "$sudoers" /etc/sudoers.d/sixb',
|
|
83
|
+
'rm -f "$sudoers"',
|
|
84
|
+
'echo "$deploy_user may run sudo systemctl reload caddy, and nothing else"',
|
|
85
|
+
"",
|
|
86
|
+
'step "Caddy routes"',
|
|
87
|
+
"caddyfile=/etc/caddy/Caddyfile",
|
|
88
|
+
"backup=/etc/caddy/Caddyfile.before-sixb-deploy",
|
|
89
|
+
"install -d -m 0755 /etc/caddy/sixb.d",
|
|
90
|
+
'install -d -m 0755 -o "$deploy_user" -g "$deploy_user" "/etc/caddy/sixb.d/$deploy_user"',
|
|
91
|
+
// Caddy allows one `*` per import pattern, so each deploy user's folder has an index file.
|
|
92
|
+
'printf \'import /etc/caddy/sixb.d/%s/*.caddy\\n\' "$deploy_user" > "/etc/caddy/sixb.d/$deploy_user.caddy"',
|
|
93
|
+
"restart_caddy=0",
|
|
94
|
+
`if [ ! -s "$caddyfile" ] || grep -qF ${shellQuote(PACKAGED_CADDYFILE)} "$caddyfile"; then`,
|
|
95
|
+
' if [ -f "$caddyfile" ]; then cp "$caddyfile" "$backup"; fi',
|
|
96
|
+
" cat > \"$caddyfile\" <<'__SIXB_CADDYFILE__'",
|
|
97
|
+
"# Managed by sixb deploy. Each deploy user's routes live in /etc/caddy/sixb.d/<user>/.",
|
|
98
|
+
"{",
|
|
99
|
+
"\t# Only root and Caddy may change the running configuration.",
|
|
100
|
+
"\tadmin unix//var/lib/caddy/admin.sock",
|
|
101
|
+
"}",
|
|
102
|
+
"",
|
|
103
|
+
"import /etc/caddy/sixb.d/*.caddy",
|
|
104
|
+
"__SIXB_CADDYFILE__",
|
|
105
|
+
// A restart, not a reload: the admin address itself moves.
|
|
106
|
+
" restart_caddy=1",
|
|
107
|
+
"elif ! grep -qF 'import /etc/caddy/sixb.d/*.caddy' \"$caddyfile\"; then",
|
|
108
|
+
' cp "$caddyfile" "$backup"',
|
|
109
|
+
" printf '\\n# Routes written by sixb deploy, one folder per deploy user.\\nimport /etc/caddy/sixb.d/*.caddy\\n' >> \"$caddyfile\"",
|
|
110
|
+
' echo "Kept this server\'s Caddyfile and added one import; the previous one is $backup."',
|
|
111
|
+
"fi",
|
|
112
|
+
'if ! caddy validate --config "$caddyfile" --adapter caddyfile > /tmp/sixb-caddy-validate.log 2>&1; then',
|
|
113
|
+
" tail -n 5 /tmp/sixb-caddy-validate.log >&2",
|
|
114
|
+
' if [ -f "$backup" ]; then cp "$backup" "$caddyfile"; fi',
|
|
115
|
+
' echo "Caddy rejected the configuration; the previous one is back in place." >&2',
|
|
116
|
+
" exit 1",
|
|
117
|
+
"fi",
|
|
118
|
+
'if [ "$restart_caddy" = 1 ]; then systemctl restart caddy; else systemctl reload caddy; fi',
|
|
119
|
+
'echo "/etc/caddy/sixb.d/$deploy_user"',
|
|
120
|
+
"",
|
|
121
|
+
'step "Checks"',
|
|
122
|
+
// Reported, not changed: editing sshd or the firewall is how people lock themselves out.
|
|
123
|
+
"sshd -T 2> /dev/null | grep -qx 'passwordauthentication yes' &&",
|
|
124
|
+
' echo "Warning: SSH accepts passwords. Set PasswordAuthentication no in /etc/ssh/sshd_config." || true',
|
|
125
|
+
"sshd -T 2> /dev/null | grep -qx 'permitrootlogin yes' &&",
|
|
126
|
+
' echo "Warning: root can log in with a password. Set PermitRootLogin prohibit-password." || true',
|
|
127
|
+
"if command -v ufw > /dev/null && ufw status 2> /dev/null | grep -q '^Status: active'; then",
|
|
128
|
+
" for port in 80 443; do",
|
|
129
|
+
' ufw status | grep -qE "^$port(/tcp)?\\s+ALLOW" ||',
|
|
130
|
+
' echo "Warning: the firewall blocks port $port, which Caddy needs. Run: sudo ufw allow $port/tcp"',
|
|
131
|
+
" done",
|
|
132
|
+
"fi",
|
|
133
|
+
'echo "Done."',
|
|
134
|
+
].join("\n")
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The public key to authorize for deploys: the one given, else the first key SSH would offer to
|
|
139
|
+
* the server that has a `.pub` beside it, else the first key in the SSH agent.
|
|
140
|
+
*/
|
|
141
|
+
export async function pickPublicKey(input: {
|
|
142
|
+
readonly key?: string
|
|
143
|
+
readonly identityFiles: readonly string[]
|
|
144
|
+
}): Promise<{ readonly text: string; readonly source: string }> {
|
|
145
|
+
if (input.key) {
|
|
146
|
+
const path = input.key.endsWith(".pub") ? input.key : `${input.key}.pub`
|
|
147
|
+
return { text: (await Bun.file(path).text()).trim(), source: path }
|
|
148
|
+
}
|
|
149
|
+
for (const identity of input.identityFiles) {
|
|
150
|
+
const path = `${identity}.pub`
|
|
151
|
+
if (
|
|
152
|
+
await access(path).then(
|
|
153
|
+
() => true,
|
|
154
|
+
() => false
|
|
155
|
+
)
|
|
156
|
+
) {
|
|
157
|
+
return { text: (await Bun.file(path).text()).trim(), source: path }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const agent = Bun.spawn(["ssh-add", "-L"], { stdout: "pipe", stderr: "ignore" })
|
|
161
|
+
const first = (await new Response(agent.stdout).text()).split("\n").find((line) => line.trim())
|
|
162
|
+
if ((await agent.exited) === 0 && first) return { text: first.trim(), source: "your SSH agent" }
|
|
163
|
+
throw new Error(
|
|
164
|
+
"[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`."
|
|
165
|
+
)
|
|
166
|
+
}
|
package/src/shell.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Quotes a value as one POSIX shell word. */
|
|
2
|
+
export function shellQuote(value: string): string {
|
|
3
|
+
return `'${value.replaceAll("'", `'"'"'`)}'`
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** A shell command that writes `content` to `path`, whatever bytes it holds. */
|
|
7
|
+
export function writeFileCommand(path: string, content: string): string {
|
|
8
|
+
const encoded = Buffer.from(content, "utf8").toString("base64")
|
|
9
|
+
return `printf '%s' ${shellQuote(encoded)} | base64 -d > ${shellQuote(path)}`
|
|
10
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { homedir } from "node:os"
|
|
2
|
+
|
|
3
|
+
export interface ResolvedSshConfig {
|
|
4
|
+
/** The real hostname or address behind the target's host, which may be an SSH config alias. */
|
|
5
|
+
readonly hostname: string
|
|
6
|
+
readonly port: number
|
|
7
|
+
/** The host SSH jumps through first, when the config sets one. */
|
|
8
|
+
readonly proxyJump?: string
|
|
9
|
+
/** Identity files SSH would offer, in order, with `~` expanded. */
|
|
10
|
+
readonly identityFiles: readonly string[]
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** What OpenSSH makes of a destination once its config applies, from `ssh -G`. */
|
|
14
|
+
export async function resolveSshConfig(destination: string): Promise<ResolvedSshConfig> {
|
|
15
|
+
const child = Bun.spawn(["ssh", "-G", destination], { stdout: "pipe", stderr: "pipe" })
|
|
16
|
+
const [exitCode, output] = await Promise.all([child.exited, new Response(child.stdout).text()])
|
|
17
|
+
if (exitCode !== 0) throw new Error(`[SshTarget] ssh -G ${destination} failed.`)
|
|
18
|
+
|
|
19
|
+
let hostname = destination.split("@").at(-1) ?? destination
|
|
20
|
+
let port = 22
|
|
21
|
+
let proxyJump: string | undefined
|
|
22
|
+
const identityFiles: string[] = []
|
|
23
|
+
for (const line of output.split("\n")) {
|
|
24
|
+
const [key, ...rest] = line.split(" ")
|
|
25
|
+
const value = rest.join(" ")
|
|
26
|
+
if (key === "hostname" && value) hostname = value
|
|
27
|
+
if (key === "port" && Number(value) > 0) port = Number(value)
|
|
28
|
+
// `ssh -G` prints `none` for a host reached directly.
|
|
29
|
+
if ((key === "proxyjump" || key === "proxycommand") && value && value !== "none") {
|
|
30
|
+
proxyJump = value
|
|
31
|
+
}
|
|
32
|
+
if (key === "identityfile" && value) identityFiles.push(value.replace(/^~(?=\/)/, homedir()))
|
|
33
|
+
}
|
|
34
|
+
return { hostname, port, identityFiles, ...(proxyJump ? { proxyJump } : {}) }
|
|
35
|
+
}
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { isIPv6 } from "node:net"
|
|
2
|
+
import type {
|
|
3
|
+
DeployAccess,
|
|
4
|
+
DeployAccessKey,
|
|
5
|
+
DeployCheck,
|
|
6
|
+
DeployCheckContext,
|
|
7
|
+
DeployCi,
|
|
8
|
+
DeployCiCredential,
|
|
9
|
+
DeployContext,
|
|
10
|
+
DeployControlAction,
|
|
11
|
+
DeployHttpServiceName,
|
|
12
|
+
DeployListenAddress,
|
|
13
|
+
DeployLogsOptions,
|
|
14
|
+
DeployOperationContext,
|
|
15
|
+
DeployRelease,
|
|
16
|
+
DeploySetupContext,
|
|
17
|
+
DeploySource,
|
|
18
|
+
DeployStatus,
|
|
19
|
+
DeployTarget,
|
|
20
|
+
} from "@sixb/core/deploy"
|
|
21
|
+
import { addKey, listKeys, removeKeys, removeKeysWhere } from "./access"
|
|
22
|
+
import { checkDns, runChecks } from "./check"
|
|
23
|
+
import { generateCiKey, knownHostsLines, readHostKeys, renderCiInstall } from "./ci"
|
|
24
|
+
import { controlServices, deployRelease, readStatus, streamLogs } from "./operations"
|
|
25
|
+
import { pickPublicKey, renderAdminScript } from "./setup"
|
|
26
|
+
import { shellQuote } from "./shell"
|
|
27
|
+
import { resolveSshConfig } from "./ssh-config"
|
|
28
|
+
import { RemoteScriptError, type RemoteShell, SshShell } from "./transport"
|
|
29
|
+
|
|
30
|
+
export interface SshTargetOptions {
|
|
31
|
+
/** The server: a hostname, an IP address, or a `Host` alias from your SSH config. */
|
|
32
|
+
readonly host: string
|
|
33
|
+
/**
|
|
34
|
+
* The Linux user the deployment runs as. Projects under one user can read each other's files,
|
|
35
|
+
* so give a project its own user to wall it off from the others on the server. Defaults to
|
|
36
|
+
* `"sixb"`.
|
|
37
|
+
*/
|
|
38
|
+
readonly user?: string
|
|
39
|
+
/**
|
|
40
|
+
* Local ports for the HTTP services, which Caddy on the server forwards to. Set them when
|
|
41
|
+
* projects share a server, so that each has its own. Defaults: atlas 3000, app 3001, api 3002.
|
|
42
|
+
*/
|
|
43
|
+
readonly ports?: Readonly<Partial<Record<DeployHttpServiceName, number>>>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const OPTIONS = ["host", "user", "ports"] as const
|
|
47
|
+
|
|
48
|
+
const DEFAULT_USER = "sixb"
|
|
49
|
+
|
|
50
|
+
const DEFAULT_PORTS = {
|
|
51
|
+
atlas: 3000,
|
|
52
|
+
app: 3001,
|
|
53
|
+
api: 3002,
|
|
54
|
+
} as const satisfies Record<DeployHttpServiceName, number>
|
|
55
|
+
|
|
56
|
+
/** Services listen on loopback only: Caddy on the same server is their one way in. */
|
|
57
|
+
const LISTEN_HOST = "127.0.0.1"
|
|
58
|
+
|
|
59
|
+
/** A Linux account name `useradd` accepts. */
|
|
60
|
+
const USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/
|
|
61
|
+
|
|
62
|
+
/** A server reached over SSH, where Caddy routes each domain to its service. */
|
|
63
|
+
export class SshTarget implements DeployTarget {
|
|
64
|
+
readonly kind = "ssh"
|
|
65
|
+
readonly host: string
|
|
66
|
+
readonly user: string
|
|
67
|
+
readonly location: string
|
|
68
|
+
readonly #ports: Readonly<Record<DeployHttpServiceName, number>>
|
|
69
|
+
|
|
70
|
+
constructor(options: SshTargetOptions) {
|
|
71
|
+
if (typeof options !== "object" || options === null) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
'[SshTarget] Pass options, such as `new SshTarget({ host: "203.0.113.10" })`.'
|
|
74
|
+
)
|
|
75
|
+
}
|
|
76
|
+
for (const key of Object.keys(options)) {
|
|
77
|
+
if (!(OPTIONS as readonly string[]).includes(key)) {
|
|
78
|
+
throw new Error(`[SshTarget] Unknown option '${key}'. Available: ${OPTIONS.join(", ")}.`)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
this.host = validateHost(options.host)
|
|
83
|
+
this.user = validateUser(options.user ?? DEFAULT_USER)
|
|
84
|
+
this.location = `${this.user}@${this.host}`
|
|
85
|
+
this.#ports = { ...DEFAULT_PORTS, ...validatePorts(options.ports) }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
listenAddress(service: DeployHttpServiceName): DeployListenAddress {
|
|
89
|
+
return { host: LISTEN_HOST, port: this.#ports[service] }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
deploy(release: DeployRelease, source: DeploySource, context: DeployContext): Promise<void> {
|
|
93
|
+
return this.#connected((shell) => deployRelease(shell, this.user, release, source, context))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
status(context: DeployOperationContext): Promise<DeployStatus> {
|
|
97
|
+
return this.#connected((shell) => readStatus(shell, context.name))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
logs(options: DeployLogsOptions, context: DeployOperationContext): Promise<void> {
|
|
101
|
+
// Following in a terminal attaches it, so Ctrl-C stops the remote reader too.
|
|
102
|
+
const terminal = options.follow && Boolean(process.stdin.isTTY && process.stdout.isTTY)
|
|
103
|
+
return this.#connected((shell) => streamLogs(shell, context.name, { ...options, terminal }))
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
control(
|
|
107
|
+
action: DeployControlAction,
|
|
108
|
+
service: string | undefined,
|
|
109
|
+
context: DeployOperationContext
|
|
110
|
+
): Promise<void> {
|
|
111
|
+
return this.#connected((shell) => controlServices(shell, context.name, action, service))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]> {
|
|
115
|
+
const { hostname } = await resolveSshConfig(this.location)
|
|
116
|
+
const dns = checkDns(release, hostname)
|
|
117
|
+
let server: DeployCheck[]
|
|
118
|
+
try {
|
|
119
|
+
server = await this.#connected(async (shell) => [
|
|
120
|
+
{ id: "ssh", label: "SSH", status: "ok" as const, detail: this.location },
|
|
121
|
+
...(await runChecks(shell, {
|
|
122
|
+
name: context.name,
|
|
123
|
+
projectPath: context.projectPath,
|
|
124
|
+
ports: release.services.flatMap((service) =>
|
|
125
|
+
service.http ? [{ service: service.name, port: service.http.port }] : []
|
|
126
|
+
),
|
|
127
|
+
location: this.location,
|
|
128
|
+
})),
|
|
129
|
+
])
|
|
130
|
+
} catch (error) {
|
|
131
|
+
server = [sshCheck(this.location, error)]
|
|
132
|
+
}
|
|
133
|
+
return [...server, ...(await dns)]
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Prepares the server as the admin login when the deploy user or the server is not set up
|
|
138
|
+
* yet, then the project as the deploy user. Running it again changes nothing that is right.
|
|
139
|
+
*/
|
|
140
|
+
async setup(release: DeployRelease, context: DeploySetupContext): Promise<void> {
|
|
141
|
+
const before = await this.check(release, context)
|
|
142
|
+
const serverFixes = before.filter(
|
|
143
|
+
(check) =>
|
|
144
|
+
(check.status === "fixable" && check.id !== "project.env") ||
|
|
145
|
+
(check.id === "ssh" && check.status !== "ok")
|
|
146
|
+
)
|
|
147
|
+
const unreachable = before.find((check) => check.id === "ssh" && check.status === "manual")
|
|
148
|
+
if (unreachable) {
|
|
149
|
+
throw new Error(`[SshTarget] ${unreachable.detail}`)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (serverFixes.length > 0) {
|
|
153
|
+
const admin = context.admin ?? "root"
|
|
154
|
+
const { identityFiles } = await resolveSshConfig(this.location)
|
|
155
|
+
const key = await pickPublicKey({ key: context.key, identityFiles })
|
|
156
|
+
context.write(
|
|
157
|
+
`Setting up ${this.host} as ${admin}, authorizing ${key.source} for ${this.user}.`
|
|
158
|
+
)
|
|
159
|
+
await runAsAdmin(
|
|
160
|
+
`${admin}@${this.host}`,
|
|
161
|
+
admin === "root",
|
|
162
|
+
renderAdminScript({ user: this.user, publicKey: key.text, admin })
|
|
163
|
+
)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
context.write(`Preparing ${context.name} as ${this.user}.`)
|
|
167
|
+
await this.#connected((shell) =>
|
|
168
|
+
shell.run(
|
|
169
|
+
[
|
|
170
|
+
`project="$HOME"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,
|
|
171
|
+
'mkdir -p "$project"',
|
|
172
|
+
'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi',
|
|
173
|
+
].join("\n")
|
|
174
|
+
)
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
readonly access: DeployAccess = {
|
|
179
|
+
list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),
|
|
180
|
+
add: (key) => this.#connected((shell) => addKey(shell, key)).then(withoutLine),
|
|
181
|
+
remove: (match) =>
|
|
182
|
+
this.#connected(async (shell) => (await removeKeys(shell, match)).map(withoutLine)),
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
readonly ci: DeployCi = {
|
|
186
|
+
create: (job, context) => this.#createCiKey(job, context.name),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* A key for one CI job, allowed to run commands and nothing else (no forwarding, no terminal),
|
|
191
|
+
* with the server's host keys pinned so CI never trusts an address on first sight.
|
|
192
|
+
*/
|
|
193
|
+
async #createCiKey(job: string, name: string): Promise<DeployCiCredential> {
|
|
194
|
+
const ssh = await resolveSshConfig(this.location)
|
|
195
|
+
if (ssh.proxyJump) {
|
|
196
|
+
throw new Error(
|
|
197
|
+
`[SshTarget] Your SSH config reaches ${this.host} through ${ssh.proxyJump}, and CI connects ` +
|
|
198
|
+
"directly. Set `host` to an address CI can reach."
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
// One comment per job and deployment: it is how a later run finds the keys it replaces.
|
|
202
|
+
const comment = `sixb-ci:${name}@${job}`
|
|
203
|
+
const pair = await generateCiKey(comment)
|
|
204
|
+
const { key, hostKeys } = await this.#connected(async (shell) => ({
|
|
205
|
+
hostKeys: await readHostKeys(shell),
|
|
206
|
+
key: await addKey(shell, pair.publicKey, "restrict"),
|
|
207
|
+
}))
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
description: `${key.fingerprint} for ${this.location}, restricted to running commands`,
|
|
211
|
+
secrets: {
|
|
212
|
+
SIXB_DEPLOY_SSH_KEY: pair.privateKey,
|
|
213
|
+
SIXB_DEPLOY_KNOWN_HOSTS: knownHostsLines(hostKeys, ssh.hostname, ssh.port).join("\n"),
|
|
214
|
+
},
|
|
215
|
+
install: renderCiInstall({ host: this.host, hostname: ssh.hostname, port: ssh.port }),
|
|
216
|
+
retireOthers: () =>
|
|
217
|
+
this.#connected(async (shell) =>
|
|
218
|
+
(
|
|
219
|
+
await removeKeysWhere(
|
|
220
|
+
shell,
|
|
221
|
+
(other) => other.comment === comment && other.fingerprint !== key.fingerprint
|
|
222
|
+
)
|
|
223
|
+
).map(withoutLine)
|
|
224
|
+
),
|
|
225
|
+
revoke: () =>
|
|
226
|
+
this.#connected(async (shell) => {
|
|
227
|
+
await removeKeysWhere(shell, (other) => other.fingerprint === key.fingerprint)
|
|
228
|
+
}),
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async #connected<T>(work: (shell: RemoteShell) => Promise<T>): Promise<T> {
|
|
233
|
+
const shell = await SshShell.open(this.location)
|
|
234
|
+
try {
|
|
235
|
+
return await work(shell)
|
|
236
|
+
} finally {
|
|
237
|
+
await shell.close()
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function validateHost(value: unknown): string {
|
|
243
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
244
|
+
throw new Error("[SshTarget] host must be the server's hostname or IP address.")
|
|
245
|
+
}
|
|
246
|
+
const host = value.trim()
|
|
247
|
+
if (host.includes("@")) {
|
|
248
|
+
throw new Error(
|
|
249
|
+
`[SshTarget] host '${host}' includes a user. Set the host alone, and the user with \`user\`.`
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
// `ssh` reads an argument that starts with `-` as an option, not a host.
|
|
253
|
+
if (host.startsWith("-") || /[\s/\\]/.test(host)) {
|
|
254
|
+
throw new Error(`[SshTarget] host '${host}' is not a hostname or IP address.`)
|
|
255
|
+
}
|
|
256
|
+
if (host.includes(":") && !isIPv6(host)) {
|
|
257
|
+
throw new Error(
|
|
258
|
+
`[SshTarget] host '${host}' includes a port. For an SSH port other than 22, add a Host ` +
|
|
259
|
+
"entry with that Port to your SSH config and use its name as the host."
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
return host
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function validateUser(value: unknown): string {
|
|
266
|
+
if (value === "root") {
|
|
267
|
+
throw new Error(
|
|
268
|
+
"[SshTarget] Deployments never run as root. Use a deploy user without sudo, such as the " +
|
|
269
|
+
'default "sixb".'
|
|
270
|
+
)
|
|
271
|
+
}
|
|
272
|
+
if (typeof value !== "string" || !USER_PATTERN.test(value)) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
`[SshTarget] user ${JSON.stringify(value)} is not a Linux user name. Use lowercase ` +
|
|
275
|
+
"letters, digits, underscores, and hyphens, starting with a letter or underscore."
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
return value
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function validatePorts(value: unknown): Partial<Record<DeployHttpServiceName, number>> {
|
|
282
|
+
if (value === undefined) return {}
|
|
283
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
284
|
+
throw new Error("[SshTarget] ports must be an object, such as `{ api: 3012 }`.")
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const ports: Partial<Record<DeployHttpServiceName, number>> = {}
|
|
288
|
+
for (const [service, port] of Object.entries(value)) {
|
|
289
|
+
if (!Object.hasOwn(DEFAULT_PORTS, service)) {
|
|
290
|
+
throw new Error(
|
|
291
|
+
`[SshTarget] ports.${service} is not an HTTP service. Available: api, atlas, app.`
|
|
292
|
+
)
|
|
293
|
+
}
|
|
294
|
+
// A deploy user has no privileges, and ports below 1024 need them.
|
|
295
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65_535) {
|
|
296
|
+
throw new Error(`[SshTarget] ports.${service} must be a port from 1024 to 65535.`)
|
|
297
|
+
}
|
|
298
|
+
ports[service as DeployHttpServiceName] = port
|
|
299
|
+
}
|
|
300
|
+
return ports
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** What a failed connection means for a deploy, and whether setup can fix it. */
|
|
304
|
+
function sshCheck(location: string, error: unknown): DeployCheck {
|
|
305
|
+
const message =
|
|
306
|
+
(error instanceof Error ? error.message : String(error))
|
|
307
|
+
.split("\n")[0]
|
|
308
|
+
?.replace(/^\[SshTarget\] /, "") ?? ""
|
|
309
|
+
if (error instanceof RemoteScriptError && /refused your SSH key/.test(message)) {
|
|
310
|
+
return {
|
|
311
|
+
id: "ssh",
|
|
312
|
+
label: "SSH",
|
|
313
|
+
status: "fixable",
|
|
314
|
+
detail: message,
|
|
315
|
+
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.`,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return {
|
|
319
|
+
id: "ssh",
|
|
320
|
+
label: "SSH",
|
|
321
|
+
status: "manual",
|
|
322
|
+
detail: message || `Cannot reach ${location}.`,
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function withoutLine({ type, fingerprint, comment, restricted }: DeployAccessKey): DeployAccessKey {
|
|
327
|
+
return { type, fingerprint, comment, restricted }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Runs the setup script as the admin login with the terminal attached, so sudo can ask for its
|
|
332
|
+
* password and the person running setup sees each step.
|
|
333
|
+
*/
|
|
334
|
+
async function runAsAdmin(destination: string, root: boolean, script: string): Promise<void> {
|
|
335
|
+
const command = `${root ? "" : "sudo "}bash -c ${shellQuote(script)}`
|
|
336
|
+
// LogLevel=ERROR drops the "Connection closed" line a terminal session ends with, not errors.
|
|
337
|
+
const ssh = ["ssh", "-tt", "-o", "ConnectTimeout=15", "-o", "LogLevel=ERROR"]
|
|
338
|
+
const child = Bun.spawn([...ssh, destination, command], {
|
|
339
|
+
stdio: ["inherit", "inherit", "inherit"],
|
|
340
|
+
})
|
|
341
|
+
const exitCode = await child.exited
|
|
342
|
+
if (exitCode !== 0) {
|
|
343
|
+
throw new Error(
|
|
344
|
+
`[SshTarget] Setting up the server as ${destination} failed (exit code ${exitCode}).`
|
|
345
|
+
)
|
|
346
|
+
}
|
|
347
|
+
}
|