@sixb/deploy-ssh 0.2.6 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +51 -44
  2. package/dist/check/index.d.ts +24 -0
  3. package/dist/check/index.d.ts.map +1 -0
  4. package/dist/check/judge.d.ts +23 -0
  5. package/dist/check/judge.d.ts.map +1 -0
  6. package/dist/index.js +599 -1527
  7. package/dist/index.js.map +10 -16
  8. package/dist/layout.d.ts +87 -30
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -3
  11. package/dist/operations.d.ts.map +1 -1
  12. package/dist/plan.d.ts +25 -0
  13. package/dist/plan.d.ts.map +1 -0
  14. package/dist/render.d.ts +15 -11
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +10 -4
  17. package/dist/server/manifest.d.ts.map +1 -1
  18. package/dist/server/release-host.d.ts +4 -0
  19. package/dist/server/release-host.d.ts.map +1 -0
  20. package/dist/server/release.d.ts +46 -0
  21. package/dist/server/release.d.ts.map +1 -0
  22. package/dist/server/state.d.ts +0 -4
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +8 -8
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -24
  27. package/dist/ssh-target.d.ts.map +1 -1
  28. package/dist/transport.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/bootstrap.sh +93 -0
  31. package/src/check/index.ts +117 -0
  32. package/src/check/judge.ts +299 -0
  33. package/src/check/probe.sh +99 -0
  34. package/src/layout.ts +109 -61
  35. package/src/operations.ts +105 -65
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +54 -35
  38. package/src/server/cli.ts +16 -20
  39. package/src/server/manifest.ts +13 -6
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +1 -5
  43. package/src/server/supervisor.ts +45 -238
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +43 -285
  46. package/src/transport.ts +28 -12
  47. package/dist/access.d.ts +0 -11
  48. package/dist/access.d.ts.map +0 -1
  49. package/dist/check.d.ts +0 -31
  50. package/dist/check.d.ts.map +0 -1
  51. package/dist/ci.d.ts +0 -27
  52. package/dist/ci.d.ts.map +0 -1
  53. package/dist/keys.d.ts +0 -13
  54. package/dist/keys.d.ts.map +0 -1
  55. package/dist/scripts.d.ts +0 -48
  56. package/dist/scripts.d.ts.map +0 -1
  57. package/dist/setup.d.ts +0 -32
  58. package/dist/setup.d.ts.map +0 -1
  59. package/src/access.ts +0 -107
  60. package/src/check.ts +0 -257
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -703
  64. package/src/setup.ts +0 -203
package/dist/setup.d.ts DELETED
@@ -1,32 +0,0 @@
1
- import { type RemoteShell } from "./transport";
2
- /**
3
- * Everything that needs root, run once per server and once per deploy user, safe to run again.
4
- * Afterwards the deploy user needs no sudo but reloading Caddy.
5
- *
6
- * Caddy's configuration is taken over only when it is still the one the package installed. A
7
- * server that already serves other sites keeps its configuration and gains one import line (the
8
- * old file is kept beside it), and its admin API stays where that configuration puts it.
9
- */
10
- export declare function renderAdminScript(input: {
11
- readonly user: string;
12
- readonly publicKey: string;
13
- readonly admin: string;
14
- }): string;
15
- /**
16
- * The public key to authorize for deploys: the one given, else the first key SSH would offer to
17
- * the server that has a `.pub` beside it, else the first key in the SSH agent.
18
- */
19
- export declare function pickPublicKey(input: {
20
- readonly key?: string;
21
- readonly identityFiles: readonly string[];
22
- }): Promise<{
23
- readonly text: string;
24
- readonly source: string;
25
- }>;
26
- /**
27
- * Creates the deploy's token when the server doesn't have one. This asks the server rather than
28
- * going by the checks setup started with: on a fresh server those stop at SSH, before they reach
29
- * the token. Returns whether it installed one.
30
- */
31
- export declare function ensureEnvToken(shell: RemoteShell, name: string, createToken: () => Promise<string>): Promise<boolean>;
32
- //# sourceMappingURL=setup.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":"AAGA,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAKjE;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB,GAAG,MAAM,CAoHT;AAED;;;GAGG;AACH,wBAAsB,aAAa,CAAC,KAAK,EAAE;IACzC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAA;CAC1C,GAAG,OAAO,CAAC;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAsB9D;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,WAAW,EAClB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,GACjC,OAAO,CAAC,OAAO,CAAC,CAwBlB"}
package/src/access.ts DELETED
@@ -1,107 +0,0 @@
1
- import { createHash } from "node:crypto"
2
- import type { DeployAccessKey } from "@sixb/core/deploy"
3
- import { type AuthorizedKey, parseAuthorizedKey, parsePublicKey } from "./keys"
4
- import { shellQuote } from "./shell"
5
- import type { RemoteShell } from "./transport"
6
-
7
- interface KeysFile {
8
- readonly lines: readonly string[]
9
- readonly keys: readonly AuthorizedKey[]
10
- readonly hash: string
11
- }
12
-
13
- export async function listKeys(shell: RemoteShell): Promise<AuthorizedKey[]> {
14
- return [...(await readKeysFile(shell)).keys]
15
- }
16
-
17
- /** Authorizes a public key once, with `options` (such as `restrict`) in front of it. */
18
- export async function addKey(
19
- shell: RemoteShell,
20
- text: string,
21
- options?: string
22
- ): Promise<AuthorizedKey> {
23
- const parsed = parsePublicKey(text)
24
- const key = options ? (parseAuthorizedKey(`${options} ${parsed.line}`) ?? parsed) : parsed
25
- const file = await readKeysFile(shell)
26
- if (file.keys.some((candidate) => candidate.fingerprint === key.fingerprint)) return key
27
- await rewrite(shell, [...file.lines, key.line], file.hash)
28
- return key
29
- }
30
-
31
- /** Removes the keys whose fingerprint or comment is `match`. Never removes the last one. */
32
- export async function removeKeys(shell: RemoteShell, match: string): Promise<DeployAccessKey[]> {
33
- const removed = await removeKeysWhere(
34
- shell,
35
- (key) => key.fingerprint === match || key.comment === match
36
- )
37
- if (removed.length === 0) {
38
- throw new Error(`[SshTarget] No authorized key has the fingerprint or comment '${match}'.`)
39
- }
40
- return removed
41
- }
42
-
43
- /** Removes the keys `matches` picks, if any. Never removes the last one. */
44
- export async function removeKeysWhere(
45
- shell: RemoteShell,
46
- matches: (key: AuthorizedKey) => boolean
47
- ): Promise<AuthorizedKey[]> {
48
- const file = await readKeysFile(shell)
49
- const removed = file.keys.filter(matches)
50
- if (removed.length === 0) return []
51
- if (removed.length === file.keys.length) {
52
- throw new Error(
53
- "[SshTarget] That would remove every key, and nobody could reach the deployment. " +
54
- "Add another key first."
55
- )
56
- }
57
- const gone = new Set(removed.map((key) => key.line))
58
- await rewrite(
59
- shell,
60
- file.lines.filter((line) => !gone.has(line.trim())),
61
- file.hash
62
- )
63
- return removed
64
- }
65
-
66
- async function readKeysFile(shell: RemoteShell): Promise<KeysFile> {
67
- const encoded: string[] = []
68
- await shell.run('(base64 < "$HOME/.ssh/authorized_keys" 2> /dev/null || true) | tr -d "\\n"', {
69
- onLine: (line, stream) => {
70
- if (stream === "stdout") encoded.push(line)
71
- },
72
- })
73
- const content = Buffer.from(encoded.join(""), "base64").toString("utf8")
74
- const lines = content.split("\n").filter((line, index, all) => line || index < all.length - 1)
75
- return {
76
- lines,
77
- keys: lines.flatMap((line) => parseAuthorizedKey(line) ?? []),
78
- hash: sha256(content),
79
- }
80
- }
81
-
82
- /**
83
- * Replaces `authorized_keys` through a rename, other lines untouched. Fails if the file changed
84
- * since it was read, so two people changing access at once cannot drop each other's key.
85
- */
86
- async function rewrite(shell: RemoteShell, lines: readonly string[], readHash: string) {
87
- const content = `${lines.join("\n")}\n`
88
- await shell.run(
89
- [
90
- "set -euo pipefail",
91
- 'keys="$HOME/.ssh/authorized_keys"',
92
- 'mkdir -p -m 700 "$HOME/.ssh"',
93
- 'current="$( (cat "$keys" 2> /dev/null || true) | sha256sum | cut -d" " -f1)"',
94
- `if [ "$current" != ${shellQuote(readHash)} ]; then`,
95
- ' echo "authorized_keys changed while this ran; run the command again." >&2',
96
- " exit 1",
97
- "fi",
98
- `printf '%s' ${shellQuote(Buffer.from(content).toString("base64"))} | base64 -d > "$keys.new"`,
99
- 'chmod 600 "$keys.new"',
100
- 'mv "$keys.new" "$keys"',
101
- ].join("\n")
102
- )
103
- }
104
-
105
- function sha256(content: string): string {
106
- return createHash("sha256").update(content).digest("hex")
107
- }
package/src/check.ts DELETED
@@ -1,257 +0,0 @@
1
- import { resolve4, resolve6 } from "node:dns/promises"
2
- import { isIP } from "node:net"
3
- import { posix } from "node:path"
4
- import type { DeployCheck, DeployRelease } from "@sixb/core/deploy"
5
- import { ENV_TOKEN_FILE } from "./layout"
6
- import { shellQuote } from "./shell"
7
- import type { RemoteShell } from "./transport"
8
-
9
- export const CHECK_MARKER = "__SIXB_CHECK__"
10
-
11
- /** The tools a deploy runs on the server. */
12
- const TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"]
13
-
14
- export const ENV_TOKEN_CHECK = "project.env-token"
15
-
16
- type Status = DeployCheck["status"]
17
-
18
- /**
19
- * Checks the server as the deploy user, changing nothing. Each check prints one
20
- * `__SIXB_CHECK__ id status detail` line; labels and remedies are added on this side.
21
- */
22
- export function renderCheckScript(input: {
23
- readonly name: string
24
- readonly projectPath: string
25
- readonly ports: readonly { readonly service: string; readonly port: number }[]
26
- /** A deploy writes `.env` from the project's source, so what it needs is the token instead. */
27
- readonly envFromSource?: boolean
28
- }): string {
29
- const project = posix.join(input.name, "code", input.projectPath)
30
- const sharedEnv = posix.join(input.name, "shared", ".env")
31
- const envToken = posix.join(input.name, ENV_TOKEN_FILE)
32
- return [
33
- `emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
34
- `project="$HOME"/${shellQuote(project)}`,
35
- `shared_env="$HOME"/${shellQuote(sharedEnv)}`,
36
- `manifest="$HOME"/${shellQuote(input.name)}/deploy/processes.json`,
37
- `ports_file="$HOME"/${shellQuote(input.name)}/deploy/ports.txt`,
38
- 'routes_dir="/etc/caddy/sixb.d/$USER"',
39
- `snippet="$routes_dir"/${shellQuote(`${input.name}.caddy`)}`,
40
- "",
41
- "if command -v apt-get > /dev/null && command -v systemctl > /dev/null; then",
42
- ' emit server.os ok "$(. /etc/os-release 2>/dev/null; echo "$PRETTY_NAME")"',
43
- "else",
44
- ' emit server.os manual "$(uname -s) without apt and systemd"',
45
- "fi",
46
- "",
47
- 'missing=""',
48
- `for tool in ${TOOLS.join(" ")}; do command -v "$tool" > /dev/null || missing="$missing $tool"; done`,
49
- 'if [ -n "$missing" ]; then emit server.tools fixable "missing:$missing"',
50
- 'else emit server.tools ok "Caddy $(caddy version 2>/dev/null | cut -d" " -f1), git, curl, unzip"; fi',
51
- "",
52
- // The routes keep WebSockets open through a reload with `stream_close_delay`, new in Caddy 2.7.
53
- "if command -v caddy > /dev/null; then",
54
- ' caddy_version="$(caddy version 2>/dev/null | cut -d" " -f1 | sed "s/^v//")"',
55
- ' if [ "$(printf "%s\\n" 2.7.0 "$caddy_version" | sort -V | head -n 1)" = 2.7.0 ]; then emit server.caddy ok "$caddy_version"',
56
- ' else emit server.caddy manual "$caddy_version is older than 2.7"; fi',
57
- "fi",
58
- "",
59
- 'if [ -e "/var/lib/systemd/linger/$USER" ]; then emit server.linger ok "on for $USER"',
60
- 'else emit server.linger fixable "off for $USER: services would stop when you log out"; fi',
61
- "",
62
- "if sudo -n -l /usr/bin/systemctl reload caddy > /dev/null 2>&1; then",
63
- ' emit server.reload ok "$USER may reload Caddy"',
64
- "else",
65
- ' emit server.reload fixable "$USER may not run sudo systemctl reload caddy"',
66
- "fi",
67
- "",
68
- 'problems=""',
69
- '[ -d "$routes_dir" ] && [ -w "$routes_dir" ] || problems="$problems; $routes_dir is missing or not writable"',
70
- 'grep -qsF "import $routes_dir/*.caddy" "/etc/caddy/sixb.d/$USER.caddy" || problems="$problems; /etc/caddy/sixb.d/$USER.caddy does not import it"',
71
- "grep -qsF 'import /etc/caddy/sixb.d/*.caddy' /etc/caddy/Caddyfile || problems=\"$problems; /etc/caddy/Caddyfile does not import /etc/caddy/sixb.d/*.caddy\"",
72
- 'if [ -z "$problems" ]; then emit server.routes ok "$routes_dir"',
73
- "else emit server.routes fixable \"$(printf '%s' \"$problems\" | sed 's/^; //')\"; fi",
74
- "",
75
- "if ss -ltnH 2> /dev/null | grep -qE '(127\\.0\\.0\\.1|\\[::1\\]):2019 '; then",
76
- ' emit server.admin-api warning "Caddy\'s admin API listens on localhost:2019, where any process on the server can change every route"',
77
- "else",
78
- ' emit server.admin-api ok "not on localhost:2019"',
79
- "fi",
80
- "",
81
- ...(input.envFromSource
82
- ? [
83
- `token="$HOME"/${shellQuote(envToken)}`,
84
- `if [ ! -s "$token" ]; then emit ${ENV_TOKEN_CHECK} fixable "$token has no token"`,
85
- `elif [ "$(stat -c %a "$token")" != 600 ]; then emit ${ENV_TOKEN_CHECK} fixable "$token is readable by others (mode $(stat -c %a "$token"))"`,
86
- `else emit ${ENV_TOKEN_CHECK} ok "$token"; fi`,
87
- ]
88
- : [
89
- 'env_file="$project/.env"',
90
- 'if [ -f "$shared_env" ]; then env_file="$shared_env"; fi',
91
- 'if [ ! -f "$env_file" ]; then emit project.env manual "$env_file does not exist"',
92
- 'elif [ "$(stat -c %a "$env_file")" != 600 ]; then emit project.env fixable "$env_file is readable by others (mode $(stat -c %a "$env_file"))"',
93
- 'else emit project.env ok "$env_file"; fi',
94
- ]),
95
- "",
96
- ...input.ports.flatMap(({ service, port }) => [
97
- `if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
98
- ` if grep -qx '${port}' "$ports_file" 2> /dev/null || { grep -qs '"--port",' "$manifest" && grep -A1 -s '"--port",' "$manifest" | grep -q '"${port}"'; }; then`,
99
- ` emit project.port.${service} ok "${port}, used by this deployment"`,
100
- " else",
101
- ` emit project.port.${service} manual "${port} is in use by another program"`,
102
- " fi",
103
- `elif grep -ls '127.0.0.1:${port}\\b' /etc/caddy/sixb.d/*/*.caddy 2> /dev/null | grep -qv "^$snippet$"; then`,
104
- ` emit project.port.${service} manual "${port} is routed to another deployment"`,
105
- `elif grep -lxs '${port}' "$HOME"/*/deploy/ports.txt 2> /dev/null | grep -qv "^$ports_file$"; then`,
106
- ` emit project.port.${service} manual "${port} is reserved by another deployment"`,
107
- "else",
108
- ` emit project.port.${service} ok "${port}"`,
109
- "fi",
110
- ]),
111
- "",
112
- 'free_kb="$(df -Pk "$HOME" | awk \'NR == 2 { print $4 + 0 }\')"',
113
- 'if [ "$free_kb" -lt 2097152 ]; then emit server.disk warning "$((free_kb / 1024)) MB free"',
114
- 'else emit server.disk ok "$((free_kb / 1048576)) GB free"; fi',
115
- ].join("\n")
116
- }
117
-
118
- /** Reads the check script's output into checks, with labels and remedies. */
119
- export function parseCheckOutput(
120
- lines: readonly string[],
121
- context: { readonly location: string; readonly name: string }
122
- ): DeployCheck[] {
123
- return lines.flatMap((line) => {
124
- const [marker, id, status, detail] = line.split("\t")
125
- if (marker !== CHECK_MARKER || !id || !isStatus(status)) return []
126
- return [describe(id, status, detail ?? "", context)]
127
- })
128
- }
129
-
130
- /** Where each HTTP domain resolves, against where the target is. */
131
- export async function checkDns(release: DeployRelease, hostname: string): Promise<DeployCheck[]> {
132
- const expected = isIP(hostname) ? [hostname] : await lookup(hostname)
133
- return Promise.all(
134
- release.services.flatMap((service) => {
135
- const http = service.http
136
- if (!http) return []
137
- return [
138
- (async (): Promise<DeployCheck> => {
139
- const found = await lookup(http.domain)
140
- const id = `dns.${service.name}`
141
- const label = `${service.name} DNS`
142
- if (expected.length > 0 && found.some((address) => expected.includes(address))) {
143
- return { id, label, status: "ok", detail: `${http.domain} → ${found.join(", ")}` }
144
- }
145
- const target = expected[0] ?? hostname
146
- return {
147
- id,
148
- label,
149
- status: "warning",
150
- detail:
151
- found.length > 0
152
- ? `${http.domain} → ${found.join(", ")}`
153
- : `${http.domain} does not resolve`,
154
- remedy: `Point ${http.domain} at ${target} with an ${isIP(target) === 6 ? "AAAA" : "A"} record. Until then, Caddy cannot get it a certificate.`,
155
- }
156
- })(),
157
- ]
158
- })
159
- )
160
- }
161
-
162
- /** The checks that stop a deploy. */
163
- export function blocksDeploy(check: DeployCheck): boolean {
164
- return check.status === "fixable" || check.status === "manual"
165
- }
166
-
167
- export async function runChecks(
168
- shell: RemoteShell,
169
- input: Parameters<typeof renderCheckScript>[0] & { readonly location: string }
170
- ): Promise<DeployCheck[]> {
171
- const lines: string[] = []
172
- await shell.run(renderCheckScript(input), {
173
- onLine: (line, stream) => {
174
- if (stream === "stdout") lines.push(line)
175
- },
176
- })
177
- return parseCheckOutput(lines, input)
178
- }
179
-
180
- const LABELS: Readonly<Record<string, string>> = {
181
- "server.os": "Server",
182
- "server.tools": "Server tools",
183
- "server.linger": "Services at boot",
184
- "server.caddy": "Caddy version",
185
- "server.reload": "Caddy reload",
186
- "server.routes": "Caddy routes",
187
- "server.admin-api": "Caddy admin API",
188
- "server.disk": "Disk space",
189
- "project.env": ".env",
190
- [ENV_TOKEN_CHECK]: "Source token",
191
- }
192
-
193
- function describe(
194
- id: string,
195
- status: Status,
196
- detail: string,
197
- context: { readonly location: string; readonly name: string }
198
- ): DeployCheck {
199
- const label =
200
- LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13).replace(/-/g, " ")} port` : id)
201
- const check = { id, label, status, detail }
202
- if (status === "ok") return check
203
- if (status === "fixable") return { ...check, remedy: "Run `sixb deploy setup`." }
204
- if (id === "server.os") return { ...check, remedy: "Deploy to an Ubuntu or Debian server." }
205
- if (id === "project.env") {
206
- const path = detail.replace(/ does not exist$/, "")
207
- return {
208
- ...check,
209
- remedy: `Create it with the project's settings: \`ssh ${context.location} 'install -m 600 /dev/null ${path}'\`, then edit it.`,
210
- }
211
- }
212
- if (id.startsWith("project.port.")) {
213
- return {
214
- ...check,
215
- remedy: "Give this service another port in the target's `ports` or `standbyPorts`.",
216
- }
217
- }
218
- if (id === "server.caddy") {
219
- return {
220
- ...check,
221
- remedy:
222
- "Upgrade Caddy from its own apt repository: https://caddyserver.com/docs/install#debian-ubuntu-raspbian",
223
- }
224
- }
225
- if (id === "server.admin-api") {
226
- return {
227
- ...check,
228
- remedy:
229
- "Set `admin unix//var/lib/caddy/admin.sock` in the global options of /etc/caddy/Caddyfile.",
230
- }
231
- }
232
- return check
233
- }
234
-
235
- function isStatus(value: string | undefined): value is Status {
236
- return value === "ok" || value === "fixable" || value === "manual" || value === "warning"
237
- }
238
-
239
- async function lookup(hostname: string): Promise<string[]> {
240
- const [v4, v6] = await Promise.all([settle(resolve4(hostname)), settle(resolve6(hostname))])
241
- return [...v4, ...v6]
242
- }
243
-
244
- /** A lookup's answers, or none once it fails or takes over four seconds. */
245
- async function settle(query: Promise<string[]>): Promise<string[]> {
246
- let timer: ReturnType<typeof setTimeout> | undefined
247
- try {
248
- return await Promise.race([
249
- query.catch(() => []),
250
- new Promise<string[]>((resolveTimeout) => {
251
- timer = setTimeout(() => resolveTimeout([]), 4_000)
252
- }),
253
- ])
254
- } finally {
255
- clearTimeout(timer)
256
- }
257
- }
package/src/ci.ts DELETED
@@ -1,88 +0,0 @@
1
- import { mkdtemp, readFile, rm } from "node:fs/promises"
2
- import { tmpdir } from "node:os"
3
- import { join } from "node:path"
4
- import type { RemoteShell } from "./transport"
5
-
6
- /**
7
- * A new key pair for a CI job. It is made in a directory that is removed before this returns, so
8
- * the private key exists only in memory here and, afterwards, in the CI system's secrets.
9
- */
10
- export async function generateCiKey(
11
- comment: string
12
- ): Promise<{ readonly privateKey: string; readonly publicKey: string }> {
13
- const dir = await mkdtemp(join(tmpdir(), "sixb-ci-key-"))
14
- try {
15
- const path = join(dir, "key")
16
- const child = Bun.spawn(
17
- ["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", path],
18
- {
19
- stdin: "ignore",
20
- stdout: "ignore",
21
- stderr: "pipe",
22
- }
23
- )
24
- if ((await child.exited) !== 0) {
25
- const reason = (await new Response(child.stderr).text()).trim()
26
- throw new Error(`[SshTarget] ssh-keygen could not make a key for CI: ${reason}`)
27
- }
28
- return {
29
- privateKey: await readFile(path, "utf8"),
30
- publicKey: (await readFile(`${path}.pub`, "utf8")).trim(),
31
- }
32
- } finally {
33
- await rm(dir, { recursive: true, force: true })
34
- }
35
- }
36
-
37
- /**
38
- * The server's host keys, read over a connection SSH has already checked against your own
39
- * `known_hosts`. CI trusts these instead of whatever answers at the address the first time.
40
- */
41
- export async function readHostKeys(shell: RemoteShell): Promise<string[]> {
42
- const keys: string[] = []
43
- await shell.run("cat /etc/ssh/ssh_host_*_key.pub", {
44
- onLine: (line, stream) => {
45
- const [type, key] = line.trim().split(/\s+/)
46
- if (stream === "stdout" && type && key) keys.push(`${type} ${key}`)
47
- },
48
- })
49
- if (keys.length === 0) throw new Error("[SshTarget] Could not read the server's SSH host keys.")
50
- return keys
51
- }
52
-
53
- /** `known_hosts` lines for the host keys, under the name and port CI connects to. */
54
- export function knownHostsLines(
55
- hostKeys: readonly string[],
56
- hostname: string,
57
- port: number
58
- ): string[] {
59
- const name = port === 22 ? hostname : `[${hostname}]:${port}`
60
- return hostKeys.map((key) => `${name} ${key}`)
61
- }
62
-
63
- /**
64
- * Shell lines that install the key on the CI runner, reading `SIXB_DEPLOY_SSH_KEY` and
65
- * `SIXB_DEPLOY_KNOWN_HOSTS` from the environment. `host` is what `sixb.deploy.ts` names, which may
66
- * be an alias from your SSH config; the runner gets the same alias.
67
- */
68
- export function renderCiInstall(input: {
69
- readonly host: string
70
- readonly hostname: string
71
- readonly port: number
72
- }): string[] {
73
- return [
74
- "install -d -m 700 ~/.ssh",
75
- "install -m 600 /dev/null ~/.ssh/sixb_deploy",
76
- `printf '%s\\n' "$SIXB_DEPLOY_SSH_KEY" > ~/.ssh/sixb_deploy`,
77
- `printf '%s\\n' "$SIXB_DEPLOY_KNOWN_HOSTS" > ~/.ssh/sixb_known_hosts`,
78
- "cat >> ~/.ssh/config <<'__SIXB_SSH_CONFIG__'",
79
- `Host ${input.host}`,
80
- ` HostName ${input.hostname}`,
81
- ` Port ${input.port}`,
82
- " IdentityFile ~/.ssh/sixb_deploy",
83
- " IdentitiesOnly yes",
84
- " UserKnownHostsFile ~/.ssh/sixb_known_hosts",
85
- " StrictHostKeyChecking yes",
86
- "__SIXB_SSH_CONFIG__",
87
- ]
88
- }
package/src/keys.ts DELETED
@@ -1,57 +0,0 @@
1
- import { createHash } from "node:crypto"
2
- import type { DeployAccessKey } from "@sixb/core/deploy"
3
-
4
- const KEY_TYPES = new Set([
5
- "ssh-ed25519",
6
- "ssh-rsa",
7
- "ecdsa-sha2-nistp256",
8
- "ecdsa-sha2-nistp384",
9
- "ecdsa-sha2-nistp521",
10
- "sk-ssh-ed25519@openssh.com",
11
- "sk-ecdsa-sha2-nistp256@openssh.com",
12
- ])
13
-
14
- export interface AuthorizedKey extends DeployAccessKey {
15
- /** The line as it appears in `authorized_keys`. */
16
- readonly line: string
17
- }
18
-
19
- /**
20
- * One `authorized_keys` line: optional options, then type, key, and comment. Returns `null` for
21
- * blank lines, comments, and anything that is not a public key.
22
- */
23
- export function parseAuthorizedKey(line: string): AuthorizedKey | null {
24
- const trimmed = line.trim()
25
- if (!trimmed || trimmed.startsWith("#")) return null
26
- const words = trimmed.split(/\s+/)
27
- const typeIndex = words.findIndex((word) => KEY_TYPES.has(word))
28
- if (typeIndex === -1) return null
29
- const type = words[typeIndex] ?? ""
30
- const encoded = words[typeIndex + 1] ?? ""
31
-
32
- const blob = Buffer.from(encoded, "base64")
33
- // The blob names its own type first; a key pasted under another type is not that key.
34
- const nameLength = blob.length >= 4 ? blob.readUInt32BE(0) : 0
35
- if (blob.subarray(4, 4 + nameLength).toString() !== type) return null
36
-
37
- const options = typeIndex > 0 ? words.slice(0, typeIndex).join(" ") : ""
38
- return {
39
- type,
40
- fingerprint: `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`,
41
- comment: words.slice(typeIndex + 2).join(" "),
42
- restricted: /(^|,)restrict(,|$)/.test(options),
43
- line: trimmed,
44
- }
45
- }
46
-
47
- /** Parses a public key given as text, failing with what is wrong with it. */
48
- export function parsePublicKey(text: string): AuthorizedKey {
49
- const key = parseAuthorizedKey(text)
50
- if (!key || key.line.includes("\n")) {
51
- throw new Error(
52
- "[SshTarget] That is not an SSH public key. Pass the contents of a .pub file, such as " +
53
- "`ssh-ed25519 AAAA… you@laptop`."
54
- )
55
- }
56
- return key
57
- }