@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.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -0
  3. package/dist/access.d.ts +11 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/check.d.ts +28 -0
  6. package/dist/check.d.ts.map +1 -0
  7. package/dist/ci.d.ts +27 -0
  8. package/dist/ci.d.ts.map +1 -0
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +1415 -0
  12. package/dist/index.js.map +24 -0
  13. package/dist/keys.d.ts +13 -0
  14. package/dist/keys.d.ts.map +1 -0
  15. package/dist/layout.d.ts +38 -0
  16. package/dist/layout.d.ts.map +1 -0
  17. package/dist/operations.d.ts +10 -0
  18. package/dist/operations.d.ts.map +1 -0
  19. package/dist/render.d.ts +15 -0
  20. package/dist/render.d.ts.map +1 -0
  21. package/dist/scripts.d.ts +37 -0
  22. package/dist/scripts.d.ts.map +1 -0
  23. package/dist/server/cli.d.ts +3 -0
  24. package/dist/server/cli.d.ts.map +1 -0
  25. package/dist/server/logs.d.ts +25 -0
  26. package/dist/server/logs.d.ts.map +1 -0
  27. package/dist/server/manifest.d.ts +30 -0
  28. package/dist/server/manifest.d.ts.map +1 -0
  29. package/dist/server/state.d.ts +32 -0
  30. package/dist/server/state.d.ts.map +1 -0
  31. package/dist/server/supervisor.d.ts +16 -0
  32. package/dist/server/supervisor.d.ts.map +1 -0
  33. package/dist/setup.d.ts +25 -0
  34. package/dist/setup.d.ts.map +1 -0
  35. package/dist/shell.d.ts +5 -0
  36. package/dist/shell.d.ts.map +1 -0
  37. package/dist/ssh-config.d.ts +12 -0
  38. package/dist/ssh-config.d.ts.map +1 -0
  39. package/dist/ssh-target.d.ts +39 -0
  40. package/dist/ssh-target.d.ts.map +1 -0
  41. package/dist/transport.d.ts +45 -0
  42. package/dist/transport.d.ts.map +1 -0
  43. package/dist/tsconfig.json +5 -0
  44. package/dist/update-page.d.ts +6 -0
  45. package/dist/update-page.d.ts.map +1 -0
  46. package/package.json +61 -0
  47. package/src/access.ts +107 -0
  48. package/src/check.ts +215 -0
  49. package/src/ci.ts +88 -0
  50. package/src/index.ts +2 -0
  51. package/src/keys.ts +57 -0
  52. package/src/layout.ts +69 -0
  53. package/src/operations.ts +158 -0
  54. package/src/render.ts +129 -0
  55. package/src/scripts.ts +305 -0
  56. package/src/server/cli.ts +157 -0
  57. package/src/server/logs.ts +180 -0
  58. package/src/server/manifest.ts +112 -0
  59. package/src/server/state.ts +81 -0
  60. package/src/server/supervisor.ts +542 -0
  61. package/src/setup.ts +166 -0
  62. package/src/shell.ts +10 -0
  63. package/src/ssh-config.ts +35 -0
  64. package/src/ssh-target.ts +347 -0
  65. package/src/transport.ts +211 -0
  66. package/src/update-page.ts +44 -0
package/src/keys.ts ADDED
@@ -0,0 +1,57 @@
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
+ }
package/src/layout.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { posix } from "node:path"
2
+
3
+ /**
4
+ * Where a deployment lives on its server. Everything but the Bun binaries and the Caddy route
5
+ * sits in one directory in the deploy user's home, so projects under one user never share files.
6
+ *
7
+ * ~/<name>/code the deployed commit; the project is `code/<projectPath>`
8
+ * ~/<name>/deploy lock, uploads, file list, release record, process manifest, ctl
9
+ * ~/<name>/run supervisor state, control requests, and logs
10
+ * ~/.sixb/bun/<v> Bun, shared by the user's projects that pin the same version
11
+ */
12
+ export interface DeploymentLayout {
13
+ readonly root: string
14
+ readonly code: string
15
+ readonly project: string
16
+ readonly deployDir: string
17
+ readonly incomingDir: string
18
+ readonly lock: string
19
+ readonly fileList: string
20
+ readonly manifest: string
21
+ readonly releaseRecord: string
22
+ /** Runs the server half of this package with the project's Bun and manifest. */
23
+ readonly ctl: string
24
+ readonly runDir: string
25
+ readonly logDir: string
26
+ readonly bunDir: string
27
+ readonly bun: string
28
+ readonly unitName: string
29
+ readonly unit: string
30
+ readonly caddyDir: string
31
+ readonly caddySnippet: string
32
+ }
33
+
34
+ export function deploymentLayout(input: {
35
+ readonly home: string
36
+ readonly user: string
37
+ readonly name: string
38
+ readonly projectPath: string
39
+ readonly bunVersion: string
40
+ }): DeploymentLayout {
41
+ const root = posix.join(input.home, input.name)
42
+ const code = posix.join(root, "code")
43
+ const deployDir = posix.join(root, "deploy")
44
+ const runDir = posix.join(root, "run")
45
+ const bunDir = posix.join(input.home, ".sixb", "bun", input.bunVersion)
46
+ const unitName = `sixb-${input.name}.service`
47
+ const caddyDir = posix.join("/etc/caddy/sixb.d", input.user)
48
+
49
+ return {
50
+ root,
51
+ code,
52
+ project: posix.join(code, input.projectPath),
53
+ deployDir,
54
+ incomingDir: posix.join(deployDir, "incoming"),
55
+ lock: posix.join(deployDir, "lock"),
56
+ fileList: posix.join(deployDir, "files.txt"),
57
+ manifest: posix.join(deployDir, "processes.json"),
58
+ releaseRecord: posix.join(deployDir, "release.json"),
59
+ ctl: posix.join(deployDir, "ctl"),
60
+ runDir,
61
+ logDir: posix.join(runDir, "logs"),
62
+ bunDir,
63
+ bun: posix.join(bunDir, "bun"),
64
+ unitName,
65
+ unit: posix.join(input.home, ".config", "systemd", "user", unitName),
66
+ caddyDir,
67
+ caddySnippet: posix.join(caddyDir, `${input.name}.caddy`),
68
+ }
69
+ }
@@ -0,0 +1,158 @@
1
+ import type {
2
+ DeployContext,
3
+ DeployControlAction,
4
+ DeployLogsOptions,
5
+ DeployRelease,
6
+ DeploySource,
7
+ DeployStatus,
8
+ } from "@sixb/core/deploy"
9
+ import { deploymentLayout } from "./layout"
10
+ import {
11
+ renderDeployScript,
12
+ renderPrepareScript,
13
+ renderReceiveScript,
14
+ STEP_MARKER,
15
+ } from "./scripts"
16
+ import { stripTerminalControl } from "./server/logs"
17
+ import { shellQuote } from "./shell"
18
+ import { RemoteScriptError, type RemoteShell } from "./transport"
19
+
20
+ const NOT_DEPLOYED = "__SIXB_NOT_DEPLOYED__"
21
+
22
+ /** Uploads the source, then runs the release on the server as one locked script. */
23
+ export async function deployRelease(
24
+ shell: RemoteShell,
25
+ user: string,
26
+ release: DeployRelease,
27
+ source: DeploySource,
28
+ context: DeployContext
29
+ ): Promise<void> {
30
+ const prepared = await capture(shell, renderPrepareScript(release.name, source.commit))
31
+ const [home, incoming] = prepared
32
+ if (!home || !incoming) {
33
+ throw new Error("[SshTarget] The server did not report its home directory.")
34
+ }
35
+
36
+ const layout = deploymentLayout({
37
+ home,
38
+ user,
39
+ name: release.name,
40
+ projectPath: source.projectPath,
41
+ bunVersion: release.bunVersion,
42
+ })
43
+ const { labels, script } = renderDeployScript({
44
+ release,
45
+ layout,
46
+ incoming,
47
+ record: {
48
+ commit: source.commit,
49
+ ref: source.ref,
50
+ deployedAt: new Date().toISOString(),
51
+ deployedBy: context.deployedBy,
52
+ },
53
+ })
54
+ context.report({ type: "steps", labels: ["Upload source", ...labels] })
55
+
56
+ context.report({ type: "step", index: 0, status: "running" })
57
+ for (const archive of source.archives) {
58
+ await shell.run(renderReceiveScript(incoming, archive.path), { stdin: archive.open() })
59
+ }
60
+ context.report({ type: "step", index: 0, status: "done" })
61
+
62
+ await runReportingSteps(shell, script, context)
63
+ }
64
+
65
+ /** Runs the deploy script, turning its step markers into progress and the rest into output. */
66
+ async function runReportingSteps(
67
+ shell: RemoteShell,
68
+ script: string,
69
+ context: DeployContext
70
+ ): Promise<void> {
71
+ const run = shell.run(script, {
72
+ onLine: (line) => {
73
+ const [marker, index, status] = line.split("\t")
74
+ if (marker === STEP_MARKER && (status === "start" || status === "done")) {
75
+ const step = Number(index) + 1
76
+ context.report({
77
+ type: "step",
78
+ index: step,
79
+ status: status === "start" ? "running" : "done",
80
+ })
81
+ } else {
82
+ const output = stripTerminalControl(line)
83
+ if (output.trim()) context.report({ type: "output", line: output })
84
+ }
85
+ },
86
+ })
87
+ try {
88
+ await run
89
+ } catch (error) {
90
+ // The step's output already reached `report`; repeating it here would print it twice.
91
+ if (error instanceof RemoteScriptError && error.exitCode !== 255) {
92
+ throw new Error(`[SshTarget] The step exited with code ${error.exitCode}.`)
93
+ }
94
+ throw error
95
+ }
96
+ }
97
+
98
+ export async function readStatus(shell: RemoteShell, name: string): Promise<DeployStatus> {
99
+ const lines = await capture(shell, ctlScript(name, ["status", "--json"], { allowMissing: true }))
100
+ const report = lines.find((line) => line.startsWith("{"))
101
+ if (lines.includes(NOT_DEPLOYED) || !report) {
102
+ return { release: null, running: false, processes: [] }
103
+ }
104
+ return JSON.parse(report) as DeployStatus
105
+ }
106
+
107
+ export async function streamLogs(
108
+ shell: RemoteShell,
109
+ name: string,
110
+ options: DeployLogsOptions & { readonly terminal?: boolean }
111
+ ): Promise<void> {
112
+ const args = [
113
+ "logs",
114
+ ...(options.service ? [options.service] : []),
115
+ "--tail",
116
+ String(options.tail),
117
+ ...(options.follow ? ["--follow"] : []),
118
+ ]
119
+ await shell.run(ctlScript(name, args), {
120
+ ...(options.terminal ? { terminal: true } : { onLine: (line: string) => options.write(line) }),
121
+ })
122
+ }
123
+
124
+ export async function controlServices(
125
+ shell: RemoteShell,
126
+ name: string,
127
+ action: DeployControlAction,
128
+ service: string | undefined
129
+ ): Promise<void> {
130
+ await shell.run(ctlScript(name, [action, ...(service ? [service] : [])]))
131
+ }
132
+
133
+ /** Runs the deployment's `ctl` with arguments; fails plainly when nothing is deployed yet. */
134
+ function ctlScript(
135
+ name: string,
136
+ args: readonly string[],
137
+ options: { readonly allowMissing?: boolean } = {}
138
+ ): string {
139
+ return [
140
+ `ctl="$HOME"/${shellQuote(name)}/deploy/ctl`,
141
+ 'if [ ! -x "$ctl" ]; then',
142
+ options.allowMissing
143
+ ? ` echo ${NOT_DEPLOYED}; exit 0`
144
+ : ` echo "Nothing named ${name} is deployed on this server yet." >&2; exit 1`,
145
+ "fi",
146
+ `exec "$ctl" ${args.map(shellQuote).join(" ")}`,
147
+ ].join("\n")
148
+ }
149
+
150
+ async function capture(shell: RemoteShell, script: string): Promise<string[]> {
151
+ const lines: string[] = []
152
+ await shell.run(script, {
153
+ onLine: (line, stream) => {
154
+ if (stream === "stdout") lines.push(line)
155
+ },
156
+ })
157
+ return lines
158
+ }
package/src/render.ts ADDED
@@ -0,0 +1,129 @@
1
+ import type { DeployRelease } from "@sixb/core/deploy"
2
+ import type { DeploymentLayout } from "./layout"
3
+ import type { ProcessManifest } from "./server/manifest"
4
+ import { shellQuote } from "./shell"
5
+ import { renderUpdatePage } from "./update-page"
6
+
7
+ const GENERATED = "Generated by sixb deploy. Changes are replaced on the next deploy."
8
+
9
+ /** The supervisor's view of the release: absolute commands, full environments. */
10
+ export function renderProcessManifest(
11
+ release: DeployRelease,
12
+ layout: DeploymentLayout
13
+ ): ProcessManifest {
14
+ const sixb = `${layout.project}/node_modules/.bin/sixb`
15
+ return {
16
+ version: 1,
17
+ name: release.name,
18
+ cwd: layout.project,
19
+ runDir: layout.runDir,
20
+ logDir: layout.logDir,
21
+ releasePath: layout.releaseRecord,
22
+ services: release.services.map((service) => ({
23
+ name: service.name,
24
+ processName: `${release.name}-${service.name}`,
25
+ command: layout.bun,
26
+ args:
27
+ service.command.program === "sixb"
28
+ ? [sixb, ...service.command.args]
29
+ : [...service.command.args],
30
+ env: service.env,
31
+ instances: service.instances,
32
+ killTimeoutMs: service.process.killTimeoutMs,
33
+ restartDelayMs: service.process.restartDelayMs,
34
+ ...(service.process.maxMemory ? { maxMemory: service.process.maxMemory } : {}),
35
+ })),
36
+ }
37
+ }
38
+
39
+ /** Pins the server half of this package to the project's Bun and manifest. */
40
+ export function renderCtl(layout: DeploymentLayout): string {
41
+ return [
42
+ "#!/bin/sh",
43
+ `# ${GENERATED}`,
44
+ `exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} "$@" --manifest ${shellQuote(layout.manifest)}`,
45
+ "",
46
+ ].join("\n")
47
+ }
48
+
49
+ /**
50
+ * The deployment's `systemd --user` unit. Linger starts the user's systemd at boot, so the
51
+ * unit comes back after a reboot without anyone logged in.
52
+ */
53
+ export function renderUnit(release: DeployRelease, layout: DeploymentLayout): string {
54
+ // Long enough for the supervisor to stop every process with its own kill timeout.
55
+ const stopSeconds =
56
+ Math.ceil(
57
+ Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000
58
+ ) + 10
59
+ return [
60
+ `# ${GENERATED}`,
61
+ "[Unit]",
62
+ `Description=Sixb deployment ${release.name}`,
63
+ "",
64
+ "[Service]",
65
+ "Type=simple",
66
+ `WorkingDirectory=${systemdValue(layout.project)}`,
67
+ `Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,
68
+ `ExecStart=${systemdValue(layout.ctl)} supervise`,
69
+ "Restart=always",
70
+ "RestartSec=2",
71
+ "KillSignal=SIGTERM",
72
+ `TimeoutStopSec=${stopSeconds}`,
73
+ "",
74
+ "[Install]",
75
+ "WantedBy=default.target",
76
+ "",
77
+ ].join("\n")
78
+ }
79
+
80
+ /** One site per HTTP service, forwarded to the service's loopback port. */
81
+ export function renderCaddySnippet(release: DeployRelease): string {
82
+ const sites = release.services.flatMap((service) => {
83
+ if (!service.http) return []
84
+ const pages = service.name === "app" || service.name === "atlas"
85
+ return [
86
+ [
87
+ `${service.http.domain} {`,
88
+ `\treverse_proxy ${service.http.host}:${service.http.port}`,
89
+ ...(pages ? updatePageOnProxyErrors() : []),
90
+ "}",
91
+ ].join("\n"),
92
+ ]
93
+ })
94
+ return [`# ${GENERATED}`, "", sites.join("\n\n"), ""].join("\n")
95
+ }
96
+
97
+ /**
98
+ * While the app or Atlas is down — during a deploy, or an outage — a browser asking for a page
99
+ * gets the update page instead of Caddy's bare error. Other requests keep the error.
100
+ */
101
+ function updatePageOnProxyErrors(): string[] {
102
+ return [
103
+ "\thandle_errors 502 503 504 {",
104
+ "\t\t@page {",
105
+ "\t\t\tmethod GET",
106
+ "\t\t\theader Accept *text/html*",
107
+ "\t\t}",
108
+ "\t\thandle @page {",
109
+ '\t\t\theader Content-Type "text/html; charset=utf-8"',
110
+ '\t\t\theader Cache-Control "no-store"',
111
+ '\t\t\theader Retry-After "10"',
112
+ "\t\t\trespond 503 {",
113
+ "\t\t\t\tbody <<HTML",
114
+ ...renderUpdatePage()
115
+ .split("\n")
116
+ .map((line) => `\t\t\t\t${line}`),
117
+ "\t\t\t\tHTML",
118
+ "\t\t\t}",
119
+ "\t\t}",
120
+ "\t\thandle {",
121
+ '\t\t\trespond "Service temporarily unavailable" {err.status_code}',
122
+ "\t\t}",
123
+ "\t}",
124
+ ]
125
+ }
126
+
127
+ function systemdValue(value: string): string {
128
+ return value.replace(/%/g, "%%").replace(/\s/g, "\\x20")
129
+ }