@sixb/deploy-ssh 0.2.0 → 0.2.5

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.
@@ -9,6 +9,11 @@ export interface ProcessManifest {
9
9
  readonly logDir: string;
10
10
  /** Written by the deploy; read back by `status`. */
11
11
  readonly releasePath: string;
12
+ /**
13
+ * The environment every service starts from, before its own additions: what `ctl run` gives a
14
+ * script. Absent from deployments made before scripts could run.
15
+ */
16
+ readonly env?: Readonly<Record<string, string>>;
12
17
  readonly services: readonly ProcessServiceManifest[];
13
18
  }
14
19
  export interface ProcessServiceManifest {
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../src/server/manifest.ts"],"names":[],"mappings":"AAGA,4FAA4F;AAC5F,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAA;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,qDAAqD;IACrD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,oDAAoD;IACpD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,QAAQ,EAAE,SAAS,sBAAsB,EAAE,CAAA;CACrD;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;IAChC,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,C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AAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;IAChC,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAC5B;AAED,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAEhF;AAED,wBAAgB,SAAS,CAAC,QAAQ,EAAE,eAAe,GAAG,MAAM,CAE3D;AAED,wBAAgB,UAAU,CAAC,QAAQ,EAAE,eAAe,GAAG,MAAM,CAE5D;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,MAAM,CAE7D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,SAAqB,GAAG,eAAe,CAmBjG"}
@@ -0,0 +1,23 @@
1
+ import type { ProcessManifest } from "./manifest";
2
+ /**
3
+ * `ctl run <staged> <path> [args...]`: puts an uploaded script at `path` in the deployed project and
4
+ * runs `sixb run` on it there, so its imports resolve against the deployed code, with the
5
+ * environment the deployment's services start from. The caller holds the deploy lock shared for
6
+ * the whole run, so no deploy replaces that code or migrates its storage underneath. Resolves with
7
+ * the exit code to end with.
8
+ *
9
+ * absent write it, and delete it afterwards
10
+ * identical run the deployed file in place
11
+ * different refuse: the deployed file is someone's committed work
12
+ *
13
+ * One run per path at a time: a second run of the same new file would find the first one's copy,
14
+ * and the first one's cleanup would delete it underneath the second. Each run marks its path, and
15
+ * whether it wrote the file, so a later run removes what a killed one left in the deployed code.
16
+ */
17
+ export declare function runScript(input: {
18
+ readonly manifest: ProcessManifest;
19
+ readonly staged: string;
20
+ readonly path: string;
21
+ readonly args: readonly string[];
22
+ }): Promise<number>;
23
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/server/run.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAGjD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,SAAS,CAAC,KAAK,EAAE;IACrC,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAA;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAA;CACjC,GAAG,OAAO,CAAC,MAAM,CAAC,CA4BlB"}
@@ -1,4 +1,4 @@
1
- import type { DeployAccess, DeployCheck, DeployCheckContext, DeployCi, DeployContext, DeployControlAction, DeployHttpServiceName, DeployListenAddress, DeployLogsOptions, DeployOperationContext, DeployRelease, DeploySetupContext, DeploySource, DeployStatus, DeployTarget } from "@sixb/core/deploy";
1
+ import type { DeployAccess, DeployCheck, DeployCheckContext, DeployCi, DeployContext, DeployControlAction, DeployHttpServiceName, DeployListenAddress, DeployLogsOptions, DeployOperationContext, DeployRelease, DeployScript, DeploySetupContext, DeploySource, DeployStatus, DeployTarget } from "@sixb/core/deploy";
2
2
  export interface SshTargetOptions {
3
3
  /** The server: a hostname, an IP address, or a `Host` alias from your SSH config. */
4
4
  readonly host: string;
@@ -27,6 +27,7 @@ export declare class SshTarget implements DeployTarget {
27
27
  status(context: DeployOperationContext): Promise<DeployStatus>;
28
28
  logs(options: DeployLogsOptions, context: DeployOperationContext): Promise<void>;
29
29
  control(action: DeployControlAction, service: string | undefined, context: DeployOperationContext): Promise<void>;
30
+ run(script: DeployScript, context: DeployOperationContext): Promise<number>;
30
31
  check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]>;
31
32
  /**
32
33
  * Prepares the server as the admin login when the deploy user or the server is not set up
@@ -1 +1 @@
1
- {"version":3,"file":"ssh-target.d.ts","sourceRoot":"","sources":["../src/ssh-target.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,YAAY,EAEZ,WAAW,EACX,kBAAkB,EAClB,QAAQ,EAER,aAAa,EACb,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,iBAAiB,EACjB,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,YAAY,EACZ,YAAY,EACb,MAAM,mBAAmB,CAAA;AAW1B,MAAM,WAAW,gBAAgB;IAC/B,qFAAqF;IACrF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC,CAAC,CAAA;CAC1E;AAiBD,gFAAgF;AAChF,qBAAa,SAAU,YAAW,YAAY;;IAC5C,QAAQ,CAAC,IAAI,SAAQ;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;gBAGb,OAAO,EAAE,gBAAgB;IAkBrC,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,mBAAmB;IAIlE,MAAM,CAAC,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAI3F,MAAM,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,YAAY,CAAC;IAI9D,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,sBAAsB,GAAG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AAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM;IAEjE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAS5D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAC7B;AAwED,iFAAiF;AACjF,wBAAgB,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,CAkBnE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixb/deploy-ssh",
3
- "version": "0.2.0",
3
+ "version": "0.2.5",
4
4
  "description": "Deploy a Sixb project to your own server over SSH",
5
5
  "keywords": [
6
6
  "sixb",
@@ -38,10 +38,10 @@
38
38
  "prepack": "bun run build"
39
39
  },
40
40
  "peerDependencies": {
41
- "@sixb/core": "^0.2.0"
41
+ "@sixb/core": "^0.2.5"
42
42
  },
43
43
  "devDependencies": {
44
- "@sixb/core": "0.2.0",
44
+ "@sixb/core": "0.2.5",
45
45
  "@types/bun": "latest",
46
46
  "typescript": "^5.7.0"
47
47
  },
package/src/operations.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import { randomUUID } from "node:crypto"
1
2
  import type {
2
3
  DeployContext,
3
4
  DeployControlAction,
4
5
  DeployLogsOptions,
5
6
  DeployRelease,
7
+ DeployScript,
6
8
  DeploySource,
7
9
  DeployStatus,
8
10
  } from "@sixb/core/deploy"
@@ -130,6 +132,56 @@ export async function controlServices(
130
132
  await shell.run(ctlScript(name, [action, ...(service ? [service] : [])]))
131
133
  }
132
134
 
135
+ /**
136
+ * Uploads the script, then runs it through `ctl run` in a terminal on the server: Ctrl-C reaches
137
+ * the script there, and so does a dropped connection, as a hangup. Holding the deploy lock shared
138
+ * for the whole run keeps a deploy from replacing the code it imports or migrating its storage;
139
+ * runs share it with each other. Resolves with the script's exit code.
140
+ */
141
+ export async function runDeployScript(
142
+ shell: RemoteShell,
143
+ name: string,
144
+ script: DeployScript
145
+ ): Promise<number> {
146
+ const root = `"$HOME"/${shellQuote(name)}`
147
+ const staged = `${root}/deploy/runs/${randomUUID()}`
148
+ await shell.run(
149
+ [
150
+ `if [ ! -x ${root}/deploy/ctl ]; then`,
151
+ ` echo "Nothing named ${name} is deployed on this server yet." >&2; exit 1`,
152
+ "fi",
153
+ "umask 077",
154
+ `mkdir -p ${root}/deploy/runs`,
155
+ // An upload whose run never started is left behind; a day later it goes.
156
+ `find ${root}/deploy/runs -type f -mmin +1440 -delete 2> /dev/null || true`,
157
+ `cat > ${staged}`,
158
+ ].join("\n"),
159
+ { stdin: new Blob([Uint8Array.from(script.source)]).stream() }
160
+ )
161
+
162
+ const run = [
163
+ `cd ${root}`,
164
+ `exec 9> ${root}/deploy/lock`,
165
+ "if ! flock -s -n 9; then",
166
+ ` echo "Waiting for a deploy of ${name} to finish…" >&2`,
167
+ "fi",
168
+ "if ! flock -s -w 600 9; then",
169
+ ` echo "A deploy of ${name} has held its lock for 10 minutes." >&2`,
170
+ ` rm -f ${staged}`,
171
+ " exit 1",
172
+ "fi",
173
+ `exec ${root}/deploy/ctl run ${staged} ${[script.path, ...script.args].map(shellQuote).join(" ")}`,
174
+ ].join("\n")
175
+ try {
176
+ await shell.run(run, { terminal: true })
177
+ return 0
178
+ } catch (error) {
179
+ // 255 is OpenSSH's own failure; any other code is the script's.
180
+ if (error instanceof RemoteScriptError && error.exitCode !== 255) return error.exitCode
181
+ throw error
182
+ }
183
+ }
184
+
133
185
  /** Runs the deployment's `ctl` with arguments; fails plainly when nothing is deployed yet. */
134
186
  function ctlScript(
135
187
  name: string,
package/src/render.ts CHANGED
@@ -19,6 +19,7 @@ export function renderProcessManifest(
19
19
  runDir: layout.runDir,
20
20
  logDir: layout.logDir,
21
21
  releasePath: layout.releaseRecord,
22
+ env: release.env,
22
23
  services: release.services.map((service) => ({
23
24
  name: service.name,
24
25
  processName: `${release.name}-${service.name}`,
package/src/scripts.ts CHANGED
@@ -122,10 +122,10 @@ function renderTakeLock(layout: DeploymentLayout): string {
122
122
  return [
123
123
  `exec 9>${shellQuote(layout.lock)}`,
124
124
  "if ! flock -n 9; then",
125
- ' echo "Waiting for another deploy of this project to finish…"',
125
+ ' echo "Waiting for another deploy or script run of this project to finish…"',
126
126
  "fi",
127
127
  "if ! flock -w 600 9; then",
128
- ' echo "Another deploy of this project has held its lock for 10 minutes." >&2',
128
+ ' echo "Another deploy or script run of this project has held its lock for 10 minutes." >&2',
129
129
  " exit 1",
130
130
  "fi",
131
131
  ].join("\n")
package/src/server/cli.ts CHANGED
@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises"
3
3
  import type { DeployRecord, DeployStatus } from "@sixb/core/deploy"
4
4
  import { followLogFiles, type LogLine, readRecentLogLines, renderProcessLogLine } from "./logs"
5
5
  import { loadProcessManifest, type ProcessManifest, statePath } from "./manifest"
6
+ import { runScript } from "./run"
6
7
  import { isMissing, isPidRunning, readProcessState } from "./state"
7
8
  import { runSupervisor, type SupervisorCommand, sendSupervisorCommand } from "./supervisor"
8
9
 
@@ -14,6 +15,7 @@ import { runSupervisor, type SupervisorCommand, sendSupervisorCommand } from "./
14
15
  * status [--json] [--check] --check exits 1 unless every process is running
15
16
  * logs [service] [--tail n] [--follow]
16
17
  * restart|start|stop [service]
18
+ * run <staged> <path> [args...] run an uploaded script with `sixb run`; see ./run.ts
17
19
  */
18
20
  const argv = process.argv.slice(2)
19
21
 
@@ -25,6 +27,17 @@ try {
25
27
  }
26
28
 
27
29
  async function main(): Promise<void> {
30
+ // A script's arguments are anything, `--manifest` included; `ctl` appends the real one last.
31
+ if (argv[0] === "run") {
32
+ const [, staged, path, ...args] = argv.slice(0, -2)
33
+ const manifestPath = argv.at(-1)
34
+ if (argv.at(-2) !== "--manifest" || !manifestPath || !staged || !path) {
35
+ throw new Error("[SshTarget] Usage: run <staged> <path> [args...] --manifest <path>")
36
+ }
37
+ const manifest = await loadProcessManifest(manifestPath)
38
+ return process.exit(await runScript({ manifest, staged, path, args }))
39
+ }
40
+
28
41
  const manifestPath = option("--manifest")
29
42
  if (!manifestPath) throw new Error("[SshTarget] --manifest is required.")
30
43
  const [command, service] = positionals()
@@ -12,6 +12,11 @@ export interface ProcessManifest {
12
12
  readonly logDir: string
13
13
  /** Written by the deploy; read back by `status`. */
14
14
  readonly releasePath: string
15
+ /**
16
+ * The environment every service starts from, before its own additions: what `ctl run` gives a
17
+ * script. Absent from deployments made before scripts could run.
18
+ */
19
+ readonly env?: Readonly<Record<string, string>>
15
20
  readonly services: readonly ProcessServiceManifest[]
16
21
  }
17
22
 
@@ -57,6 +62,7 @@ export function parseProcessManifest(value: unknown, source = "process manifest"
57
62
  runDir: string(manifest.runDir, `${source}.runDir`),
58
63
  logDir: string(manifest.logDir, `${source}.logDir`),
59
64
  releasePath: string(manifest.releasePath, `${source}.releasePath`),
65
+ ...(manifest.env === undefined ? {} : { env: environment(manifest.env, `${source}.env`) }),
60
66
  services: manifest.services.map((service, index) =>
61
67
  parseService(service, `${source}.services[${index}]`)
62
68
  ),
@@ -68,19 +74,14 @@ function parseService(value: unknown, source: string): ProcessServiceManifest {
68
74
  if (!Array.isArray(service.args) || service.args.some((arg) => typeof arg !== "string")) {
69
75
  throw new Error(`[SshTarget] ${source}.args must be an array of strings`)
70
76
  }
71
- const env = record(service.env, `${source}.env`)
72
- for (const [key, variable] of Object.entries(env)) {
73
- if (typeof variable !== "string") {
74
- throw new Error(`[SshTarget] ${source}.env.${key} must be a string`)
75
- }
76
- }
77
+ const env = environment(service.env, `${source}.env`)
77
78
 
78
79
  return {
79
80
  name: string(service.name, `${source}.name`),
80
81
  processName: string(service.processName, `${source}.processName`),
81
82
  command: string(service.command, `${source}.command`),
82
83
  args: service.args,
83
- env: env as Record<string, string>,
84
+ env,
84
85
  instances: positiveInteger(service.instances, `${source}.instances`),
85
86
  killTimeoutMs: positiveInteger(service.killTimeoutMs, `${source}.killTimeoutMs`),
86
87
  restartDelayMs: positiveInteger(service.restartDelayMs, `${source}.restartDelayMs`),
@@ -90,6 +91,15 @@ function parseService(value: unknown, source: string): ProcessServiceManifest {
90
91
  }
91
92
  }
92
93
 
94
+ function environment(value: unknown, source: string): Record<string, string> {
95
+ const env = record(value, source)
96
+ for (const [key, variable] of Object.entries(env)) {
97
+ if (typeof variable !== "string")
98
+ throw new Error(`[SshTarget] ${source}.${key} must be a string`)
99
+ }
100
+ return env as Record<string, string>
101
+ }
102
+
93
103
  function record(value: unknown, source: string): Record<string, unknown> {
94
104
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
95
105
  throw new Error(`[SshTarget] ${source} must be an object`)
@@ -0,0 +1,246 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdir, readdir, readFile, realpath, rm, rmdir, stat, writeFile } from "node:fs/promises"
3
+ import { constants } from "node:os"
4
+ import { dirname, join, relative, resolve } from "node:path"
5
+ import type { ProcessManifest } from "./manifest"
6
+ import { isPidRunning } from "./state"
7
+
8
+ /**
9
+ * `ctl run <staged> <path> [args...]`: puts an uploaded script at `path` in the deployed project and
10
+ * runs `sixb run` on it there, so its imports resolve against the deployed code, with the
11
+ * environment the deployment's services start from. The caller holds the deploy lock shared for
12
+ * the whole run, so no deploy replaces that code or migrates its storage underneath. Resolves with
13
+ * the exit code to end with.
14
+ *
15
+ * absent write it, and delete it afterwards
16
+ * identical run the deployed file in place
17
+ * different refuse: the deployed file is someone's committed work
18
+ *
19
+ * One run per path at a time: a second run of the same new file would find the first one's copy,
20
+ * and the first one's cleanup would delete it underneath the second. Each run marks its path, and
21
+ * whether it wrote the file, so a later run removes what a killed one left in the deployed code.
22
+ */
23
+ export async function runScript(input: {
24
+ readonly manifest: ProcessManifest
25
+ readonly staged: string
26
+ readonly path: string
27
+ readonly args: readonly string[]
28
+ }): Promise<number> {
29
+ const { manifest, staged, path } = input
30
+ try {
31
+ assertProjectPath(path)
32
+ if (!manifest.env) {
33
+ throw new Error(
34
+ `[SshTarget] ${manifest.name} was deployed before sixb run could run scripts on it. Deploy it again.`
35
+ )
36
+ }
37
+ const project = manifest.cwd
38
+ const marks = join(manifest.runDir, "scripts")
39
+ await removeAbandoned(marks, project)
40
+ const mark = await claimPath(marks, path)
41
+ try {
42
+ const target = resolve(project, path)
43
+ const created = await placeScript(project, target, path, await readFile(staged))
44
+ if (created) await mark.wrote(await stat(target))
45
+ try {
46
+ return await runSixb(project, path, input.args, manifest.env)
47
+ } finally {
48
+ if (created) await removeCreated(target, created)
49
+ }
50
+ } finally {
51
+ await mark.release()
52
+ }
53
+ } finally {
54
+ await rm(staged, { force: true })
55
+ }
56
+ }
57
+
58
+ /** A path relative to the project with forward slashes, which `sixb run` records as given. */
59
+ function assertProjectPath(path: string): void {
60
+ if (
61
+ path === "" ||
62
+ path.startsWith("/") ||
63
+ path.includes("\\") ||
64
+ path.includes("\0") ||
65
+ path.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
66
+ ) {
67
+ throw new Error(`[SshTarget] '${path}' is not a path inside the project.`)
68
+ }
69
+ }
70
+
71
+ /** What a run records about its path while it runs. */
72
+ interface Mark {
73
+ readonly pid: number
74
+ readonly path: string
75
+ /** The file the run wrote, so it is the run's to remove while it is still that file. */
76
+ readonly wrote?: { readonly ino: number; readonly mtimeMs: number }
77
+ }
78
+
79
+ /**
80
+ * Marks `path` as running under this process's id until `release`. A mark whose process is gone
81
+ * was left by a run that was killed: `removeAbandoned` clears it first.
82
+ */
83
+ async function claimPath(
84
+ marks: string,
85
+ path: string
86
+ ): Promise<{ wrote(file: Mark["wrote"]): Promise<void>; release(): Promise<void> }> {
87
+ const file = join(marks, `${createHash("sha256").update(path).digest("hex")}.json`)
88
+ const record = (wrote?: Mark["wrote"]) =>
89
+ JSON.stringify({ pid: process.pid, path, ...(wrote ? { wrote } : {}) } satisfies Mark)
90
+ try {
91
+ await writeFile(file, record(), { flag: "wx" })
92
+ } catch (error) {
93
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
94
+ throw new Error(`[SshTarget] ${path} is already running on the deployment.`)
95
+ }
96
+ return {
97
+ wrote: (written) =>
98
+ writeFile(file, record(written && { ino: written.ino, mtimeMs: written.mtimeMs })),
99
+ release: () => rm(file, { force: true }),
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Clears the marks of runs whose process is gone, removing each file such a run wrote unless
105
+ * something has replaced it since, such as a deploy of the same path.
106
+ */
107
+ async function removeAbandoned(marks: string, project: string): Promise<void> {
108
+ await mkdir(marks, { recursive: true })
109
+ for (const name of await readdir(marks)) {
110
+ const file = join(marks, name)
111
+ const mark = await readMark(file)
112
+ if (mark && isPidRunning(mark.pid)) continue
113
+ if (mark?.wrote) {
114
+ try {
115
+ assertProjectPath(mark.path)
116
+ const target = resolve(project, mark.path)
117
+ const current = await stat(target)
118
+ if (current.ino === mark.wrote.ino && current.mtimeMs === mark.wrote.mtimeMs) {
119
+ await rm(target, { force: true })
120
+ }
121
+ } catch {
122
+ // Gone already, or a mark this code did not write: nothing to remove.
123
+ }
124
+ }
125
+ await rm(file, { force: true })
126
+ }
127
+ }
128
+
129
+ async function readMark(file: string): Promise<Mark | null> {
130
+ try {
131
+ const mark = JSON.parse(await readFile(file, "utf8")) as Partial<Mark>
132
+ if (typeof mark.pid !== "number" || typeof mark.path !== "string") return null
133
+ const wrote = mark.wrote
134
+ return typeof wrote?.ino === "number" && typeof wrote.mtimeMs === "number"
135
+ ? { pid: mark.pid, path: mark.path, wrote: { ino: wrote.ino, mtimeMs: wrote.mtimeMs } }
136
+ : { pid: mark.pid, path: mark.path }
137
+ } catch {
138
+ return null
139
+ }
140
+ }
141
+
142
+ /** Where the script was written, for cleanup: the first directory it had to make. */
143
+ interface Created {
144
+ readonly firstDirectory: string | null
145
+ }
146
+
147
+ async function placeScript(
148
+ project: string,
149
+ target: string,
150
+ path: string,
151
+ source: Buffer
152
+ ): Promise<Created | null> {
153
+ // Checked before anything is made: a symlinked directory in the deployed code must not carry
154
+ // the script, or the directories made for it, out of the project.
155
+ const existing = await nearestExisting(dirname(target))
156
+ if (relative(await realpath(project), await realpath(existing)).startsWith("..")) {
157
+ throw new Error(`[SshTarget] '${path}' leads outside the deployed project.`)
158
+ }
159
+ const firstDirectory = existing === dirname(target) ? null : firstMissing(target, existing)
160
+ await mkdir(dirname(target), { recursive: true })
161
+
162
+ try {
163
+ await writeFile(target, source, { flag: "wx", mode: 0o600 })
164
+ return { firstDirectory }
165
+ } catch (error) {
166
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
167
+ }
168
+
169
+ const deployed = await readFile(target)
170
+ if (!deployed.equals(source)) {
171
+ throw new Error(
172
+ `[SshTarget] The deployed ${path} differs from yours. Rename your copy, or deploy it first.`
173
+ )
174
+ }
175
+ return null
176
+ }
177
+
178
+ async function nearestExisting(directory: string): Promise<string> {
179
+ let current = directory
180
+ while (!(await stat(current).catch(() => null)) && dirname(current) !== current) {
181
+ current = dirname(current)
182
+ }
183
+ return current
184
+ }
185
+
186
+ /** The directory just below `existing` on the way to `target`. */
187
+ function firstMissing(target: string, existing: string): string {
188
+ let current = dirname(target)
189
+ while (dirname(current) !== existing) current = dirname(current)
190
+ return current
191
+ }
192
+
193
+ async function removeCreated(target: string, created: Created): Promise<void> {
194
+ await rm(target, { force: true })
195
+ if (!created.firstDirectory) return
196
+ // Only directories left empty: whatever the script wrote next to itself stays.
197
+ for (let current = dirname(target); ; current = dirname(current)) {
198
+ const removed = await rmdir(current).then(
199
+ () => true,
200
+ () => false
201
+ )
202
+ if (!removed || current === created.firstDirectory) return
203
+ }
204
+ }
205
+
206
+ /**
207
+ * The project's own `sixb run`, on this Bun, with the environment the release's services start
208
+ * from; the project's `.env` fills in the rest, as it does for them. It shares the terminal, so
209
+ * Ctrl-C reaches it from there. A dropped connection hangs up only the session leader, which is
210
+ * this process, so the hangup is passed on, as is a SIGTERM sent here.
211
+ */
212
+ async function runSixb(
213
+ project: string,
214
+ path: string,
215
+ args: readonly string[],
216
+ env: Readonly<Record<string, string>>
217
+ ): Promise<number> {
218
+ const child = Bun.spawn(
219
+ [process.execPath, join(project, "node_modules", ".bin", "sixb"), "run", path, ...args],
220
+ {
221
+ cwd: project,
222
+ stdio: ["inherit", "inherit", "inherit"],
223
+ env: {
224
+ ...process.env,
225
+ ...env,
226
+ PATH: `${dirname(process.execPath)}:${process.env.PATH ?? ""}`,
227
+ },
228
+ }
229
+ )
230
+ const ignore = () => {}
231
+ const hangUp = () => child.kill("SIGHUP")
232
+ const terminate = () => child.kill("SIGTERM")
233
+ process.on("SIGINT", ignore)
234
+ process.on("SIGHUP", hangUp)
235
+ process.on("SIGTERM", terminate)
236
+ try {
237
+ const exitCode = await child.exited
238
+ const signal = child.signalCode
239
+ if (signal === null) return exitCode
240
+ return 128 + (typeof signal === "number" ? signal : (constants.signals[signal] ?? 0))
241
+ } finally {
242
+ process.off("SIGINT", ignore)
243
+ process.off("SIGHUP", hangUp)
244
+ process.off("SIGTERM", terminate)
245
+ }
246
+ }
package/src/ssh-target.ts CHANGED
@@ -13,6 +13,7 @@ import type {
13
13
  DeployLogsOptions,
14
14
  DeployOperationContext,
15
15
  DeployRelease,
16
+ DeployScript,
16
17
  DeploySetupContext,
17
18
  DeploySource,
18
19
  DeployStatus,
@@ -22,7 +23,13 @@ import { addKey, listKeys, removeKeys, removeKeysWhere } from "./access"
22
23
  import { checkDns, ENV_TOKEN_CHECK, runChecks } from "./check"
23
24
  import { generateCiKey, knownHostsLines, readHostKeys, renderCiInstall } from "./ci"
24
25
  import { ENV_TOKEN_FILE } from "./layout"
25
- import { controlServices, deployRelease, readStatus, streamLogs } from "./operations"
26
+ import {
27
+ controlServices,
28
+ deployRelease,
29
+ readStatus,
30
+ runDeployScript,
31
+ streamLogs,
32
+ } from "./operations"
26
33
  import { ensureEnvToken, pickPublicKey, renderAdminScript } from "./setup"
27
34
  import { shellQuote } from "./shell"
28
35
  import { resolveSshConfig } from "./ssh-config"
@@ -111,6 +118,10 @@ export class SshTarget implements DeployTarget {
111
118
  return this.#connected((shell) => controlServices(shell, context.name, action, service))
112
119
  }
113
120
 
121
+ run(script: DeployScript, context: DeployOperationContext): Promise<number> {
122
+ return this.#connected((shell) => runDeployScript(shell, context.name, script))
123
+ }
124
+
114
125
  async check(release: DeployRelease, context: DeployCheckContext): Promise<DeployCheck[]> {
115
126
  const { hostname } = await resolveSshConfig(this.location)
116
127
  const dns = checkDns(release, hostname)
package/src/transport.ts CHANGED
@@ -111,7 +111,7 @@ export class LocalShell implements RemoteShell {
111
111
  constructor(private readonly env: Readonly<Record<string, string>> = {}) {}
112
112
 
113
113
  async run(script: string, options: RunOptions = {}): Promise<void> {
114
- const inline = options.stdin !== undefined
114
+ const inline = options.stdin !== undefined || options.terminal === true
115
115
  await runProcess(inline ? ["bash", "-c", script] : ["bash", "-s"], {
116
116
  ...options,
117
117
  ...(inline ? {} : { stdin: new Blob([script]).stream() }),
@@ -127,7 +127,10 @@ async function runProcess(
127
127
  options: RunOptions & { readonly env?: Readonly<Record<string, string>> }
128
128
  ): Promise<void> {
129
129
  if (options.terminal) {
130
- const child = Bun.spawn([...command], { stdio: ["inherit", "inherit", "inherit"] })
130
+ const child = Bun.spawn([...command], {
131
+ stdio: ["inherit", "inherit", "inherit"],
132
+ env: { ...process.env, ...options.env },
133
+ })
131
134
  const exitCode = await child.exited
132
135
  if (exitCode !== 0) throw new RemoteScriptError(`exited with code ${exitCode}`, exitCode)
133
136
  return