@sixb/deploy-ssh 0.1.4 → 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.
package/README.md CHANGED
@@ -30,6 +30,7 @@ Each deployment lives in its deploy user's home:
30
30
 
31
31
  ```
32
32
  ~/<name>/code the deployed commit, with the project's .env
33
+ ~/<name>/env-token the token a deploy pulls .env with, if the project has a source
33
34
  ~/<name>/deploy the lock, uploads, file list, release record, process manifest, and ctl
34
35
  ~/<name>/run process state and logs
35
36
  ~/.sixb/bun/<v> Bun, shared by the user's projects on the same version
package/dist/check.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { DeployCheck, DeployRelease } from "@sixb/core/deploy";
2
2
  import type { RemoteShell } from "./transport";
3
3
  export declare const CHECK_MARKER = "__SIXB_CHECK__";
4
+ export declare const ENV_TOKEN_CHECK = "project.env-token";
4
5
  /**
5
6
  * Checks the server as the deploy user, changing nothing. Each check prints one
6
7
  * `__SIXB_CHECK__ id status detail` line; labels and remedies are added on this side.
@@ -12,6 +13,8 @@ export declare function renderCheckScript(input: {
12
13
  readonly service: string;
13
14
  readonly port: number;
14
15
  }[];
16
+ /** A deploy writes `.env` from the project's source, so what it needs is the token instead. */
17
+ readonly envFromSource?: boolean;
15
18
  }): string;
16
19
  /** Reads the check script's output into checks, with labels and remedies. */
17
20
  export declare function parseCheckOutput(lines: readonly string[], context: {
@@ -1 +1 @@
1
- {"version":3,"file":"check.d.ts","sourceRoot":"","sources":["../src/check.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAEnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C,eAAO,MAAM,YAAY,mBAAmB,CAAA;AAO5C;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAA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,MAAM,CAAA;IAC5B,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC9E,+FAA+F;IAC/F,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAA;CACjC,GAAG,MAAM,CA0ET;AAED,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,OAAO,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC5D,WAAW,EAAE,CAMf;AAED,oEAAoE;AACpE,wBAAsB,QAAQ,CAAC,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CA6B/F;AAED,qCAAqC;AACrC,wBAAgB,YAAY,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAExD;AAED,wBAAsB,SAAS,CAC7B,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,UAAU,CAAC,OAAO,iBAAiB,CAAC,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC7E,OAAO,CAAC,WAAW,EAAE,CAAC,CAQxB"}
package/dist/index.js CHANGED
@@ -132,11 +132,49 @@ function sha256(content) {
132
132
  // src/check.ts
133
133
  import { resolve4, resolve6 } from "dns/promises";
134
134
  import { isIP } from "net";
135
+ import { posix as posix2 } from "path";
136
+
137
+ // src/layout.ts
135
138
  import { posix } from "path";
139
+ var ENV_TOKEN_FILE = "env-token";
140
+ function deploymentLayout(input) {
141
+ const root = posix.join(input.home, input.name);
142
+ const code = posix.join(root, "code");
143
+ const deployDir = posix.join(root, "deploy");
144
+ const runDir = posix.join(root, "run");
145
+ const bunDir = posix.join(input.home, ".sixb", "bun", input.bunVersion);
146
+ const unitName = `sixb-${input.name}.service`;
147
+ const caddyDir = posix.join("/etc/caddy/sixb.d", input.user);
148
+ return {
149
+ root,
150
+ code,
151
+ envToken: posix.join(root, ENV_TOKEN_FILE),
152
+ project: posix.join(code, input.projectPath),
153
+ deployDir,
154
+ incomingDir: posix.join(deployDir, "incoming"),
155
+ lock: posix.join(deployDir, "lock"),
156
+ fileList: posix.join(deployDir, "files.txt"),
157
+ manifest: posix.join(deployDir, "processes.json"),
158
+ releaseRecord: posix.join(deployDir, "release.json"),
159
+ ctl: posix.join(deployDir, "ctl"),
160
+ runDir,
161
+ logDir: posix.join(runDir, "logs"),
162
+ bunDir,
163
+ bun: posix.join(bunDir, "bun"),
164
+ unitName,
165
+ unit: posix.join(input.home, ".config", "systemd", "user", unitName),
166
+ caddyDir,
167
+ caddySnippet: posix.join(caddyDir, `${input.name}.caddy`)
168
+ };
169
+ }
170
+
171
+ // src/check.ts
136
172
  var CHECK_MARKER = "__SIXB_CHECK__";
137
173
  var TOOLS = ["git", "curl", "unzip", "tar", "flock", "sha256sum", "caddy"];
174
+ var ENV_TOKEN_CHECK = "project.env-token";
138
175
  function renderCheckScript(input) {
139
- const project = posix.join(input.name, "code", input.projectPath);
176
+ const project = posix2.join(input.name, "code", input.projectPath);
177
+ const envToken = posix2.join(input.name, ENV_TOKEN_FILE);
140
178
  return [
141
179
  `emit() { printf '${CHECK_MARKER}\\t%s\\t%s\\t%s\\n' "$1" "$2" "$(printf '%s' "$3" | tr '\\t\\n' ' ')"; }`,
142
180
  `project="$HOME"/${shellQuote(project)}`,
@@ -177,9 +215,16 @@ function renderCheckScript(input) {
177
215
  ' emit server.admin-api ok "not on localhost:2019"',
178
216
  "fi",
179
217
  "",
180
- 'if [ ! -f "$project/.env" ]; then emit project.env manual "$project/.env does not exist"',
181
- 'elif [ "$(stat -c %a "$project/.env")" != 600 ]; then emit project.env fixable "$project/.env is readable by others (mode $(stat -c %a "$project/.env"))"',
182
- 'else emit project.env ok "$project/.env"; fi',
218
+ ...input.envFromSource ? [
219
+ `token="$HOME"/${shellQuote(envToken)}`,
220
+ `if [ ! -s "$token" ]; then emit ${ENV_TOKEN_CHECK} fixable "$token has no token"`,
221
+ `elif [ "$(stat -c %a "$token")" != 600 ]; then emit ${ENV_TOKEN_CHECK} fixable "$token is readable by others (mode $(stat -c %a "$token"))"`,
222
+ `else emit ${ENV_TOKEN_CHECK} ok "$token"; fi`
223
+ ] : [
224
+ 'if [ ! -f "$project/.env" ]; then emit project.env manual "$project/.env does not exist"',
225
+ 'elif [ "$(stat -c %a "$project/.env")" != 600 ]; then emit project.env fixable "$project/.env is readable by others (mode $(stat -c %a "$project/.env"))"',
226
+ 'else emit project.env ok "$project/.env"; fi'
227
+ ],
183
228
  "",
184
229
  ...input.ports.flatMap(({ service, port }) => [
185
230
  `if ss -ltnH "sport = :${port}" 2> /dev/null | grep -q .; then`,
@@ -253,7 +298,8 @@ var LABELS = {
253
298
  "server.routes": "Caddy routes",
254
299
  "server.admin-api": "Caddy admin API",
255
300
  "server.disk": "Disk space",
256
- "project.env": ".env"
301
+ "project.env": ".env",
302
+ [ENV_TOKEN_CHECK]: "Source token"
257
303
  };
258
304
  function describe(id, status, detail, context) {
259
305
  const label = LABELS[id] ?? (id.startsWith("project.port.") ? `${id.slice(13)} port` : id);
@@ -363,37 +409,8 @@ function renderCiInstall(input) {
363
409
  ];
364
410
  }
365
411
 
366
- // src/layout.ts
367
- import { posix as posix2 } from "path";
368
- function deploymentLayout(input) {
369
- const root = posix2.join(input.home, input.name);
370
- const code = posix2.join(root, "code");
371
- const deployDir = posix2.join(root, "deploy");
372
- const runDir = posix2.join(root, "run");
373
- const bunDir = posix2.join(input.home, ".sixb", "bun", input.bunVersion);
374
- const unitName = `sixb-${input.name}.service`;
375
- const caddyDir = posix2.join("/etc/caddy/sixb.d", input.user);
376
- return {
377
- root,
378
- code,
379
- project: posix2.join(code, input.projectPath),
380
- deployDir,
381
- incomingDir: posix2.join(deployDir, "incoming"),
382
- lock: posix2.join(deployDir, "lock"),
383
- fileList: posix2.join(deployDir, "files.txt"),
384
- manifest: posix2.join(deployDir, "processes.json"),
385
- releaseRecord: posix2.join(deployDir, "release.json"),
386
- ctl: posix2.join(deployDir, "ctl"),
387
- runDir,
388
- logDir: posix2.join(runDir, "logs"),
389
- bunDir,
390
- bun: posix2.join(bunDir, "bun"),
391
- unitName,
392
- unit: posix2.join(input.home, ".config", "systemd", "user", unitName),
393
- caddyDir,
394
- caddySnippet: posix2.join(caddyDir, `${input.name}.caddy`)
395
- };
396
- }
412
+ // src/operations.ts
413
+ import { randomUUID } from "crypto";
397
414
 
398
415
  // src/update-page.ts
399
416
  function renderUpdatePage() {
@@ -448,6 +465,7 @@ function renderProcessManifest(release, layout) {
448
465
  runDir: layout.runDir,
449
466
  logDir: layout.logDir,
450
467
  releasePath: layout.releaseRecord,
468
+ env: release.env,
451
469
  services: release.services.map((service) => ({
452
470
  name: service.name,
453
471
  processName: `${release.name}-${service.name}`,
@@ -577,6 +595,7 @@ function renderDeployScript(input) {
577
595
  { label: "Apply files", body: renderApplyFiles(layout, input.incoming) },
578
596
  { label: `Install Bun ${release.bunVersion}`, body: renderInstallBun(release.bunVersion) },
579
597
  { label: "Install dependencies", body: renderInstallDependencies() },
598
+ ...release.steps.env ? [envStep(release.steps.env, layout)] : [],
580
599
  ...release.steps.build.map((command) => runStep(command)),
581
600
  { label: "Write services", body: renderWriteServices(release, layout) },
582
601
  { label: "Update routes", body: renderUpdateRoutes(release, layout) },
@@ -637,10 +656,10 @@ function renderTakeLock(layout) {
637
656
  return [
638
657
  `exec 9>${shellQuote(layout.lock)}`,
639
658
  "if ! flock -n 9; then",
640
- ' echo "Waiting for another deploy of this project to finish\u2026"',
659
+ ' echo "Waiting for another deploy or script run of this project to finish\u2026"',
641
660
  "fi",
642
661
  "if ! flock -w 600 9; then",
643
- ' echo "Another deploy of this project has held its lock for 10 minutes." >&2',
662
+ ' echo "Another deploy or script run of this project has held its lock for 10 minutes." >&2',
644
663
  " exit 1",
645
664
  "fi"
646
665
  ].join(`
@@ -720,6 +739,10 @@ function runStep(command) {
720
739
  `)
721
740
  };
722
741
  }
742
+ function envStep(command, layout) {
743
+ const step = runStep(command);
744
+ return { ...step, body: `${step.body} --token-file ${shellQuote(layout.envToken)}` };
745
+ }
723
746
  function renderStopServices() {
724
747
  return [
725
748
  'if systemctl --user is-active --quiet "$UNIT"; then',
@@ -891,7 +914,10 @@ class SshShell {
891
914
  }
892
915
  async function runProcess(command, options) {
893
916
  if (options.terminal) {
894
- const child = Bun.spawn([...command], { stdio: ["inherit", "inherit", "inherit"] });
917
+ const child = Bun.spawn([...command], {
918
+ stdio: ["inherit", "inherit", "inherit"],
919
+ env: { ...process.env, ...options.env }
920
+ });
895
921
  const exitCode = await child.exited;
896
922
  if (exitCode !== 0)
897
923
  throw new RemoteScriptError(`exited with code ${exitCode}`, exitCode);
@@ -1042,6 +1068,42 @@ async function streamLogs(shell, name, options) {
1042
1068
  async function controlServices(shell, name, action, service) {
1043
1069
  await shell.run(ctlScript(name, [action, ...service ? [service] : []]));
1044
1070
  }
1071
+ async function runDeployScript(shell, name, script) {
1072
+ const root = `"$HOME"/${shellQuote(name)}`;
1073
+ const staged = `${root}/deploy/runs/${randomUUID()}`;
1074
+ await shell.run([
1075
+ `if [ ! -x ${root}/deploy/ctl ]; then`,
1076
+ ` echo "Nothing named ${name} is deployed on this server yet." >&2; exit 1`,
1077
+ "fi",
1078
+ "umask 077",
1079
+ `mkdir -p ${root}/deploy/runs`,
1080
+ `find ${root}/deploy/runs -type f -mmin +1440 -delete 2> /dev/null || true`,
1081
+ `cat > ${staged}`
1082
+ ].join(`
1083
+ `), { stdin: new Blob([Uint8Array.from(script.source)]).stream() });
1084
+ const run = [
1085
+ `cd ${root}`,
1086
+ `exec 9> ${root}/deploy/lock`,
1087
+ "if ! flock -s -n 9; then",
1088
+ ` echo "Waiting for a deploy of ${name} to finish\u2026" >&2`,
1089
+ "fi",
1090
+ "if ! flock -s -w 600 9; then",
1091
+ ` echo "A deploy of ${name} has held its lock for 10 minutes." >&2`,
1092
+ ` rm -f ${staged}`,
1093
+ " exit 1",
1094
+ "fi",
1095
+ `exec ${root}/deploy/ctl run ${staged} ${[script.path, ...script.args].map(shellQuote).join(" ")}`
1096
+ ].join(`
1097
+ `);
1098
+ try {
1099
+ await shell.run(run, { terminal: true });
1100
+ return 0;
1101
+ } catch (error) {
1102
+ if (error instanceof RemoteScriptError && error.exitCode !== 255)
1103
+ return error.exitCode;
1104
+ throw error;
1105
+ }
1106
+ }
1045
1107
  function ctlScript(name, args, options = {}) {
1046
1108
  return [
1047
1109
  `ctl="$HOME"/${shellQuote(name)}/deploy/ctl`,
@@ -1196,6 +1258,26 @@ async function pickPublicKey(input) {
1196
1258
  return { text: first.trim(), source: "your SSH agent" };
1197
1259
  throw new Error("[SshTarget] No public key to authorize. Pass one with `--key ~/.ssh/id_ed25519.pub`.");
1198
1260
  }
1261
+ async function ensureEnvToken(shell, name, createToken) {
1262
+ const path = `"$HOME"/${shellQuote(`${name}/${ENV_TOKEN_FILE}`)}`;
1263
+ const installed = await shell.run(`[ -s ${path} ]`).then(() => true, (error) => {
1264
+ if (error instanceof RemoteScriptError && error.exitCode === 1)
1265
+ return false;
1266
+ throw error;
1267
+ });
1268
+ if (installed)
1269
+ return false;
1270
+ await shell.run([
1271
+ "set -e",
1272
+ "umask 077",
1273
+ `mkdir -p "$HOME"/${shellQuote(name)}`,
1274
+ `cat > ${path}.new`,
1275
+ `mv ${path}.new ${path}`
1276
+ ].join(`
1277
+ `), { stdin: new Blob([`${await createToken()}
1278
+ `]).stream() });
1279
+ return true;
1280
+ }
1199
1281
 
1200
1282
  // src/ssh-config.ts
1201
1283
  import { homedir } from "os";
@@ -1271,6 +1353,9 @@ class SshTarget {
1271
1353
  control(action, service, context) {
1272
1354
  return this.#connected((shell) => controlServices(shell, context.name, action, service));
1273
1355
  }
1356
+ run(script, context) {
1357
+ return this.#connected((shell) => runDeployScript(shell, context.name, script));
1358
+ }
1274
1359
  async check(release, context) {
1275
1360
  const { hostname } = await resolveSshConfig(this.location);
1276
1361
  const dns = checkDns(release, hostname);
@@ -1282,6 +1367,7 @@ class SshTarget {
1282
1367
  name: context.name,
1283
1368
  projectPath: context.projectPath,
1284
1369
  ports: release.services.flatMap((service) => service.http ? [{ service: service.name, port: service.http.port }] : []),
1370
+ envFromSource: release.steps.env !== undefined,
1285
1371
  location: this.location
1286
1372
  })
1287
1373
  ]);
@@ -1292,7 +1378,7 @@ class SshTarget {
1292
1378
  }
1293
1379
  async setup(release, context) {
1294
1380
  const before = await this.check(release, context);
1295
- const serverFixes = before.filter((check) => check.status === "fixable" && check.id !== "project.env" || check.id === "ssh" && check.status !== "ok");
1381
+ const serverFixes = before.filter((check) => check.status === "fixable" && check.id !== "project.env" && check.id !== ENV_TOKEN_CHECK || check.id === "ssh" && check.status !== "ok");
1296
1382
  const unreachable = before.find((check) => check.id === "ssh" && check.status === "manual");
1297
1383
  if (unreachable) {
1298
1384
  throw new Error(`[SshTarget] ${unreachable.detail}`);
@@ -1308,9 +1394,17 @@ class SshTarget {
1308
1394
  await this.#connected((shell) => shell.run([
1309
1395
  `project="$HOME"/${shellQuote(`${context.name}/code/${context.projectPath}`)}`,
1310
1396
  'mkdir -p "$project"',
1311
- 'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi'
1397
+ 'if [ -f "$project/.env" ]; then chmod 600 "$project/.env"; fi',
1398
+ `token="$HOME"/${shellQuote(`${context.name}/${ENV_TOKEN_FILE}`)}`,
1399
+ 'if [ -f "$token" ]; then chmod 600 "$token"; fi'
1312
1400
  ].join(`
1313
1401
  `)));
1402
+ const { createEnvToken } = context;
1403
+ if (release.steps.env && createEnvToken) {
1404
+ const installed = await this.#connected((shell) => ensureEnvToken(shell, context.name, createEnvToken));
1405
+ if (installed)
1406
+ context.write(`Installed a read-only token for ${context.name}.`);
1407
+ }
1314
1408
  }
1315
1409
  access = {
1316
1410
  list: () => this.#connected(async (shell) => (await listKeys(shell)).map(withoutLine)),
@@ -1434,4 +1528,4 @@ export {
1434
1528
  SshTarget
1435
1529
  };
1436
1530
 
1437
- //# debugId=7E4838DFE5E9997564756E2164756E21
1531
+ //# debugId=B4A600CC24E47FE664756E2164756E21