@basaltkit/deploy 0.4.1 → 0.5.1

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 (53) hide show
  1. package/README.md +284 -23
  2. package/dist/answers.d.ts +70 -0
  3. package/dist/answers.js +196 -0
  4. package/dist/apache.js +11 -2
  5. package/dist/audit.d.ts +20 -0
  6. package/dist/audit.js +26 -0
  7. package/dist/backup.d.ts +17 -1
  8. package/dist/backup.js +56 -1
  9. package/dist/bin.js +9 -1
  10. package/dist/bootstrap.d.ts +68 -18
  11. package/dist/bootstrap.js +177 -45
  12. package/dist/caddy.js +2 -1
  13. package/dist/check.js +18 -5
  14. package/dist/checks.js +1 -1
  15. package/dist/cli.d.ts +22 -1
  16. package/dist/cli.js +498 -57
  17. package/dist/compose.d.ts +1 -1
  18. package/dist/compose.js +6 -1
  19. package/dist/config.d.ts +25 -2
  20. package/dist/config.js +65 -3
  21. package/dist/context.d.ts +43 -13
  22. package/dist/context.js +50 -7
  23. package/dist/detach.d.ts +23 -0
  24. package/dist/detach.js +105 -0
  25. package/dist/env-step.d.ts +16 -1
  26. package/dist/env-step.js +61 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +179 -7
  30. package/dist/host.js +317 -42
  31. package/dist/index.d.ts +10 -5
  32. package/dist/index.js +7 -3
  33. package/dist/init.d.ts +2 -0
  34. package/dist/init.js +2 -1
  35. package/dist/install-plan.d.ts +40 -0
  36. package/dist/install-plan.js +437 -0
  37. package/dist/json-host.d.ts +32 -0
  38. package/dist/json-host.js +106 -0
  39. package/dist/lock.d.ts +45 -0
  40. package/dist/lock.js +128 -0
  41. package/dist/pipeline.d.ts +51 -3
  42. package/dist/pipeline.js +339 -173
  43. package/dist/protocol.d.ts +364 -0
  44. package/dist/protocol.js +134 -0
  45. package/dist/runs.d.ts +75 -0
  46. package/dist/runs.js +287 -0
  47. package/dist/state.d.ts +26 -13
  48. package/dist/state.js +68 -4
  49. package/dist/trust.d.ts +63 -0
  50. package/dist/trust.js +159 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +10 -0
  53. package/package.json +5 -1
package/dist/compose.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { join } from 'node:path';
2
+ import { ONCE_GLOB } from './config.js';
2
3
  import { DeployError } from './context.js';
3
4
  import { listeners } from './ports.js';
4
5
  /**
@@ -196,7 +197,11 @@ export async function runJobs(ctx, sha) {
196
197
  const lines = [];
197
198
  for (const job of composeOf(ctx).jobs ?? []) {
198
199
  if (job.once) {
199
- const seen = await ctx.host.exec('docker', composeArgs(ctx, 'run', '--rm', '--no-deps', '--entrypoint', 'sh', job.service, '-c', `ls ${job.once.exists}`), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
200
+ // The glob is $1, never part of the script: the shell expands it as a
201
+ // path pattern, it can never run as a command.
202
+ if (!ONCE_GLOB.test(job.once.exists))
203
+ throw new DeployError(`job ${job.service}: once.exists "${job.once.exists}" is not an absolute path pattern`);
204
+ const seen = await ctx.host.exec('docker', composeArgs(ctx, 'run', '--rm', '--no-deps', '--entrypoint', 'sh', job.service, '-c', 'ls -d -- $1', 'sh', job.once.exists), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
200
205
  if (seen.code === 0) {
201
206
  lines.push(`job ${job.service}: already done (${job.once.exists})`);
202
207
  continue;
package/dist/config.d.ts CHANGED
@@ -73,6 +73,14 @@ export interface DeployConfig<E extends object = EnvShape> {
73
73
  hooks?: HooksConfig;
74
74
  /** Declarative checks after the health check; a failure is a failed release, rolled back (RFC 0007 §6). */
75
75
  verify?: VerifyConfig;
76
+ /**
77
+ * Every release record already says who (`--actor` or `$USER`), from where
78
+ * (`$SSH_CONNECTION`) and how. `syslog: true` also sends one line per
79
+ * release to the system log (`logger -t basalt-deploy`).
80
+ */
81
+ audit?: {
82
+ syslog?: boolean;
83
+ };
76
84
  /** What `basalt-deploy bootstrap` sets up on a fresh server (RFC 0007 §7). */
77
85
  bootstrap?: {
78
86
  /** Swap created when RAM is under 6 GB and there is none; 0 = never. @default 4 */
@@ -322,8 +330,10 @@ export interface BackupConfig<E extends object = EnvShape> {
322
330
  */
323
331
  keep?: number;
324
332
  /**
325
- * Relative to the app directory.
326
- * @default 'backups/predeploy'
333
+ * Relative to the app directory. Unset, the dumps go to
334
+ * `<stateDir>/backups` (0700): `/var/lib/basalt/<app>/backups` once
335
+ * `install` ran — outside the checkout, so never in an image or a commit.
336
+ * @default '<stateDir>/backups'
327
337
  */
328
338
  dir?: string;
329
339
  /**
@@ -559,6 +569,19 @@ export interface DockerInfraOptions<E extends object = EnvShape> {
559
569
  */
560
570
  export declare function dockerInfra<E extends object = EnvShape>(app: string, options?: NoInfer<DockerInfraOptions<E>>): DockerInfra<E>;
561
571
  export declare const APP_NAME: RegExp;
572
+ /** `once.exists`: an absolute path with glob characters, nothing a shell would treat as syntax. */
573
+ export declare const ONCE_GLOB: RegExp;
574
+ /** A git remote name: never an option (`-…`), never a URL or a path. */
575
+ export declare const REMOTE_NAME: RegExp;
576
+ /**
577
+ * `git check-ref-format --branch`, narrowed to the characters a branch name
578
+ * needs — and never a leading `-`, which git would read as an option
579
+ * (`--upload-pack=…` runs a command).
580
+ */
581
+ export declare function isBranchName(name: unknown): boolean;
582
+ /** A relative path that stays inside its base: no absolute path, no `..`, no empty segment. */
583
+ export declare function isInsidePath(path: unknown): boolean;
584
+ export declare const DOMAIN: RegExp;
562
585
  export declare class DeployConfigError extends Error {
563
586
  readonly problems: string[];
564
587
  constructor(problems: string[]);
package/dist/config.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * its own module. A config can therefore be printed, diffed and validated
6
6
  * without running anything.
7
7
  */
8
+ import { API_PREFIX, ASK_PATH, caddyExtraProblem, CERT_NAME, envLocationProblem, isConfigRoot, isWebRoot, vhostFileProblem } from './trust.js';
8
9
  /** The entries of an env record, without the keys a mapped type left `undefined`. */
9
10
  export function definedEntries(record) {
10
11
  return Object.entries(record ?? {}).filter((entry) => entry[1] !== undefined);
@@ -102,7 +103,31 @@ export function dockerInfra(app, options = {}) {
102
103
  }
103
104
  // ── validation and server-local overrides ──────────────────────────────────
104
105
  export const APP_NAME = /^[a-z][a-z0-9-]{1,30}$/;
105
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
106
+ /** `once.exists`: an absolute path with glob characters, nothing a shell would treat as syntax. */
107
+ export const ONCE_GLOB = /^\/[A-Za-z0-9._/*?[\]-]+$/;
108
+ /** A git remote name: never an option (`-…`), never a URL or a path. */
109
+ export const REMOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
110
+ /**
111
+ * `git check-ref-format --branch`, narrowed to the characters a branch name
112
+ * needs — and never a leading `-`, which git would read as an option
113
+ * (`--upload-pack=…` runs a command).
114
+ */
115
+ export function isBranchName(name) {
116
+ if (typeof name !== 'string' || name.length === 0 || name.length > 200)
117
+ return false;
118
+ if (!/^[A-Za-z0-9._/+-]+$/.test(name))
119
+ return false;
120
+ if (/^[-/.]/.test(name) || /[/.]$/.test(name) || name.endsWith('.lock'))
121
+ return false;
122
+ return !/\.\.|\/\/|\/\.|\.lock\//.test(name);
123
+ }
124
+ /** A relative path that stays inside its base: no absolute path, no `..`, no empty segment. */
125
+ export function isInsidePath(path) {
126
+ if (typeof path !== 'string' || path === '' || path.startsWith('/') || path.includes('\0'))
127
+ return false;
128
+ return path.replace(/\/$/, '').split('/').every((segment) => segment !== '' && segment !== '..');
129
+ }
130
+ export const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
106
131
  export class DeployConfigError extends Error {
107
132
  problems;
108
133
  constructor(problems) {
@@ -122,6 +147,10 @@ export function validateConfig(typed) {
122
147
  problems.push(`app "${config.app}" must match ${APP_NAME}`);
123
148
  if (!DOMAIN.test(config.domain))
124
149
  problems.push(`domain "${config.domain}" is not a lowercase host name`);
150
+ if (config.branch !== undefined && !isBranchName(config.branch))
151
+ problems.push(`branch "${String(config.branch)}" is not a plain git branch name (no leading "-", no "..", letters, digits, . _ / + - only)`);
152
+ if (config.remote !== undefined && !REMOTE_NAME.test(config.remote))
153
+ problems.push(`remote "${String(config.remote)}" is not a git remote name (${REMOTE_NAME})`);
125
154
  // C4: the deploy only ever names what carries the app's label. `pm2 restart
126
155
  // all` once was one keystroke away from a production app that is not ours.
127
156
  if (config.runtime.kind === 'pm2') {
@@ -155,6 +184,10 @@ export function validateConfig(typed) {
155
184
  for (const key of Object.keys(rt.env))
156
185
  if (!/^[A-Z_][A-Z0-9_]*$/.test(key))
157
186
  problems.push(`runtime.env key "${key}" is not a variable name`);
187
+ for (const job of rt.jobs ?? []) {
188
+ if (job.once && !ONCE_GLOB.test(job.once.exists))
189
+ problems.push(`runtime.jobs ${job.service}: once.exists "${job.once.exists}" must be an absolute path pattern (letters, digits, . _ / - and * ? [ ])`);
190
+ }
158
191
  }
159
192
  if (config.proxy?.kind === 'apache' && config.proxy.managed === false) {
160
193
  const vhosts = config.proxy.vhosts ?? [];
@@ -171,8 +204,9 @@ export function validateConfig(typed) {
171
204
  if (config.migrate?.command && config.migrate.command.length === 0)
172
205
  problems.push('migrate.command must not be empty');
173
206
  const vhost = vhostName(config);
174
- if (vhost !== undefined && !/^[a-z0-9.-]+\.conf$/.test(vhost))
175
- problems.push(`proxy.vhost "${vhost}" must be a plain *.conf file name`);
207
+ const vhostProblem = vhost !== undefined && config.proxy?.kind === 'apache' && config.proxy.managed !== false ? vhostFileProblem(config.app, vhost) : undefined;
208
+ if (vhostProblem)
209
+ problems.push(`proxy.vhost "${vhost}" ${vhostProblem}`);
176
210
  const keys = [
177
211
  ...Object.keys(config.env.fixed ?? {}),
178
212
  ...Object.keys(config.env.generate ?? {}),
@@ -222,9 +256,37 @@ export function validateConfig(typed) {
222
256
  if (config.backup?.keep !== undefined && (!Number.isInteger(config.backup.keep) || config.backup.keep < 1)) {
223
257
  problems.push('backup.keep must be a whole number ≥ 1');
224
258
  }
259
+ if (config.backup?.dir !== undefined && !isInsidePath(config.backup.dir)) {
260
+ problems.push(`backup.dir "${config.backup.dir}" must be a path inside the checkout (relative, no "..")`);
261
+ }
225
262
  if (config.backup?.container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(config.backup.container)) {
226
263
  problems.push(`backup.container "${config.backup.container}" is not a container name`);
227
264
  }
265
+ // What install writes, as root, into Apache/Caddy configuration and hands to
266
+ // the app user: checked here and again by install on the plan (trust.ts).
267
+ if (config.proxy?.kind === 'apache' || config.proxy?.kind === 'caddy') {
268
+ const proxy = config.proxy;
269
+ // Unmanaged: root writes nothing from these two, so nothing to hold them to.
270
+ const managed = proxy.managed !== false;
271
+ if (managed && !isWebRoot(proxy.webRoot))
272
+ problems.push(`proxy.webRoot "${String(proxy.webRoot)}" must be a directory inside the checkout (relative; letters, digits, . _ -; no dot directories, not the checkout itself)`);
273
+ if (managed && (typeof proxy.apiPrefix !== 'string' || !API_PREFIX.test(proxy.apiPrefix)))
274
+ problems.push(`proxy.apiPrefix "${String(proxy.apiPrefix)}" must be a URL path such as /api`);
275
+ if (proxy.root !== undefined && !isConfigRoot(proxy.root))
276
+ problems.push(`proxy.root "${String(proxy.root)}" must be an absolute directory such as ${proxy.kind === 'apache' ? '/etc/apache2' : '/etc/caddy'}`);
277
+ if (proxy.kind === 'apache' && proxy.certName !== undefined && !CERT_NAME.test(proxy.certName))
278
+ problems.push(`proxy.certName "${proxy.certName}" is not a certificate name`);
279
+ if (proxy.kind === 'caddy' && proxy.onDemandTls && !ASK_PATH.test(proxy.onDemandTls.ask))
280
+ problems.push(`proxy.onDemandTls.ask "${proxy.onDemandTls.ask}" must be a URL path such as /tls/allowed`);
281
+ const extra = proxy.kind === 'caddy' && proxy.extra !== undefined ? caddyExtraProblem(proxy.extra) : undefined;
282
+ if (extra)
283
+ problems.push(`proxy.extra ${extra}`);
284
+ }
285
+ for (const file of [config.env.file ?? '.env', ...(config.env.mirror ?? [])]) {
286
+ const problem = typeof file === 'string' ? envLocationProblem(config.app, file) : 'must be a string';
287
+ if (problem)
288
+ problems.push(`env file ${problem}`);
289
+ }
228
290
  if (config.proxy?.kind === 'caddy' && config.tenants === 'subdomain' && !config.proxy.onDemandTls) {
229
291
  problems.push(`tenants: 'subdomain' behind caddy() needs onDemandTls: { ask: '/…' } — a certificate per tenant host, issued only for hosts the app vouches for`);
230
292
  }
package/dist/context.d.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import type { Audit } from './audit.js';
1
2
  import type { DeployConfig } from './config.js';
2
3
  import type { Host } from './host.js';
4
+ import type { ErrorCode, Finding } from './protocol.js';
3
5
  export interface DeployContext {
4
6
  config: DeployConfig;
5
7
  /** The app's checkout. */
@@ -17,15 +19,18 @@ export interface DeployContext {
17
19
  values?: Map<string, string>;
18
20
  /** Container addresses → their 127.0.0.1 form, for what runs on the host (`dockerInfra({ access: 'containers' })`). */
19
21
  hostUrls?: Array<[string, string]>;
22
+ /** Set while a locked command runs; a signal marks it, the next step boundary acts on it. */
23
+ abort?: AbortState;
24
+ /** Who runs the command, from where — stamped on every release it records. */
25
+ audit?: Audit;
20
26
  }
21
- export interface Finding {
22
- /** The RFC 0006 §5 check id (`C1`…`C10`) or a step name. */
23
- id: string;
24
- level: 'error' | 'warning';
25
- message: string;
26
- /** One line the operator can act on. */
27
- fix?: string;
27
+ export interface AbortState {
28
+ /** The first SIGINT/SIGTERM/SIGHUP heard. */
29
+ signal?: string;
30
+ /** Past the point where stopping is safe (release, rollback, install): finish, then exit. */
31
+ deferred: boolean;
28
32
  }
33
+ export type { Finding } from './protocol.js';
29
34
  /**
30
35
  * How the app user runs the deploy. Not `pnpm exec`: pnpm ≥ 12 rewrites
31
36
  * `pnpm-lock.yaml` on any command in the checkout when the lockfile came from
@@ -33,17 +38,42 @@ export interface Finding {
33
38
  */
34
39
  export declare const RUN_COMMAND = "node node_modules/@basaltkit/deploy/dist/bin.js run";
35
40
  /**
36
- * How an administrator runs `install`. The node binary is resolved by the
37
- * operator's shell BEFORE sudo: with a per-user Node (nvm, fnm, volta) root
38
- * has no `node` on its PATH — `sudo node` failed with "command not found" on
39
- * the first server. Not `pnpm exec` either: root often has no pnpm.
41
+ * The first half of `install`, run by the app user: it writes the install
42
+ * plan (data only) and prints the root command for the second half, pinned
43
+ * to this exact version. Root never runs the checkout's node_modules nor
44
+ * loads deploy.config.ts (RFC 0006 §11.4).
40
45
  */
41
- export declare const INSTALL_COMMAND = "sudo \"$(command -v node)\" node_modules/@basaltkit/deploy/dist/bin.js install --user=\"$USER\"";
46
+ export declare const INSTALL_COMMAND = "node node_modules/@basaltkit/deploy/dist/bin.js install-plan";
47
+ /**
48
+ * The second half, as root, with a copy of the tool root owns: npx from
49
+ * outside the checkout (inside it, npx would pick the checkout's own copy,
50
+ * which install refuses) and with root's HOME (`-H`), so the download lands
51
+ * in root's cache, not the user's.
52
+ */
53
+ export declare function rootInstallCommand(version: string, plan: string, user: string): string;
54
+ /** A word an administrator pastes into a root shell: as is when plain, else single-quoted. */
55
+ export declare function shellQuote(word: string): string;
42
56
  export declare const errors: (findings: Finding[]) => Finding[];
57
+ /** How a finding reads on a terminal: `[id] message` and the fix under it. */
58
+ export declare const formatFinding: (finding: Finding) => string;
59
+ /** Findings as text — or structured, to an output that takes them (RFC 0008 `finding` events). */
43
60
  export declare function report(host: Host, findings: Finding[]): void;
44
61
  export declare function detectPackageManager(host: Host, dir: string): Promise<DeployContext['pm']>;
45
62
  export declare function resolveStateDir(host: Host, config: DeployConfig, dir: string): Promise<string>;
46
63
  export declare class DeployError extends Error {
47
64
  readonly findings: Finding[];
48
- constructor(message: string, findings?: Finding[]);
65
+ readonly code?: ErrorCode | undefined;
66
+ readonly hint?: string | undefined;
67
+ /**
68
+ * @param code what the machine protocol reports (RFC 0008 §4.2); the CLI maps the classes otherwise
69
+ * @param hint one line on what to do, for a program (the message says it to a person)
70
+ */
71
+ constructor(message: string, findings?: Finding[], code?: ErrorCode | undefined, hint?: string | undefined);
72
+ }
73
+ /** A signal stopped the command at a step boundary (after putting the code back). */
74
+ export declare class DeployAbortedError extends DeployError {
75
+ readonly signal: string;
76
+ constructor(signal: string, detail?: string);
49
77
  }
78
+ /** Throws {@link DeployAbortedError} when a signal arrived and stopping is still safe. */
79
+ export declare function throwIfAborted(ctx: DeployContext): void;
package/dist/context.js CHANGED
@@ -8,16 +8,36 @@ const BIN = 'node_modules/@basaltkit/deploy/dist/bin.js';
8
8
  */
9
9
  export const RUN_COMMAND = `node ${BIN} run`;
10
10
  /**
11
- * How an administrator runs `install`. The node binary is resolved by the
12
- * operator's shell BEFORE sudo: with a per-user Node (nvm, fnm, volta) root
13
- * has no `node` on its PATH — `sudo node` failed with "command not found" on
14
- * the first server. Not `pnpm exec` either: root often has no pnpm.
11
+ * The first half of `install`, run by the app user: it writes the install
12
+ * plan (data only) and prints the root command for the second half, pinned
13
+ * to this exact version. Root never runs the checkout's node_modules nor
14
+ * loads deploy.config.ts (RFC 0006 §11.4).
15
15
  */
16
- export const INSTALL_COMMAND = `sudo "$(command -v node)" ${BIN} install --user="$USER"`;
16
+ export const INSTALL_COMMAND = `node ${BIN} install-plan`;
17
+ /**
18
+ * The second half, as root, with a copy of the tool root owns: npx from
19
+ * outside the checkout (inside it, npx would pick the checkout's own copy,
20
+ * which install refuses) and with root's HOME (`-H`), so the download lands
21
+ * in root's cache, not the user's.
22
+ */
23
+ export function rootInstallCommand(version, plan, user) {
24
+ return `cd / && sudo -H npx --yes --package=@basaltkit/deploy@${version} -- basalt-deploy install --plan=${shellQuote(plan)} --user=${user}`;
25
+ }
26
+ /** A word an administrator pastes into a root shell: as is when plain, else single-quoted. */
27
+ export function shellQuote(word) {
28
+ return /^[A-Za-z0-9_./=:@%+-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
29
+ }
17
30
  export const errors = (findings) => findings.filter((f) => f.level === 'error');
31
+ /** How a finding reads on a terminal: `[id] message` and the fix under it. */
32
+ export const formatFinding = (finding) => `[${finding.id}] ${finding.message}${finding.fix ? `\n → ${finding.fix}` : ''}`;
33
+ /** Findings as text — or structured, to an output that takes them (RFC 0008 `finding` events). */
18
34
  export function report(host, findings) {
19
35
  for (const finding of findings) {
20
- const line = `[${finding.id}] ${finding.message}${finding.fix ? `\n → ${finding.fix}` : ''}`;
36
+ if (host.out.finding) {
37
+ host.out.finding(finding);
38
+ continue;
39
+ }
40
+ const line = formatFinding(finding);
21
41
  if (finding.level === 'error')
22
42
  host.out.error(line);
23
43
  else
@@ -51,9 +71,32 @@ export async function resolveStateDir(host, config, dir) {
51
71
  }
52
72
  export class DeployError extends Error {
53
73
  findings;
54
- constructor(message, findings = []) {
74
+ code;
75
+ hint;
76
+ /**
77
+ * @param code what the machine protocol reports (RFC 0008 §4.2); the CLI maps the classes otherwise
78
+ * @param hint one line on what to do, for a program (the message says it to a person)
79
+ */
80
+ constructor(message, findings = [], code, hint) {
55
81
  super(message);
56
82
  this.findings = findings;
83
+ this.code = code;
84
+ this.hint = hint;
57
85
  this.name = 'DeployError';
58
86
  }
59
87
  }
88
+ /** A signal stopped the command at a step boundary (after putting the code back). */
89
+ export class DeployAbortedError extends DeployError {
90
+ signal;
91
+ constructor(signal, detail) {
92
+ super(`stopped by ${signal}${detail ? ` — ${detail}` : ''}`);
93
+ this.signal = signal;
94
+ this.name = 'DeployAbortedError';
95
+ }
96
+ }
97
+ /** Throws {@link DeployAbortedError} when a signal arrived and stopping is still safe. */
98
+ export function throwIfAborted(ctx) {
99
+ const abort = ctx.abort;
100
+ if (abort?.signal && !abort.deferred)
101
+ throw new DeployAbortedError(abort.signal);
102
+ }
@@ -0,0 +1,23 @@
1
+ import type { AnswerChannel } from './answers.js';
2
+ import { type DeployContext } from './context.js';
3
+ import type { Reporter } from './events.js';
4
+ /** The marker a detached child is started with; `--run-id` is refused without it. */
5
+ export declare const DETACHED_CHILD_ENV = "BASALT_DEPLOY_DETACHED_CHILD";
6
+ /** How long the parent waits for the child to hold the lock. */
7
+ export declare const DETACH_CONFIRM_MS = 30000;
8
+ export interface DetachRequest {
9
+ command: 'run' | 'rollback';
10
+ /** The flags the child gets again (never an answer). */
11
+ forward: string[];
12
+ answers?: AnswerChannel;
13
+ /** `node` and this package's bin.js. */
14
+ execPath: string;
15
+ binPath: string;
16
+ }
17
+ /**
18
+ * `run --detach` / `rollback --detach` (RFC 0008 §8.2), the parent: it never
19
+ * takes the lock. Everything the child would need to ask is checked here
20
+ * first; the child is started in its own session with the answers on its
21
+ * stdin only; the parent returns once the child holds the lock.
22
+ */
23
+ export declare function detach(ctx: DeployContext, request: DetachRequest, reporter: Reporter): Promise<number>;
package/dist/detach.js ADDED
@@ -0,0 +1,105 @@
1
+ import { DeployError } from './context.js';
2
+ import { formatValue, UnwritableValueError } from './dotenv.js';
3
+ import { planEnv, readEnv } from './env-step.js';
4
+ import { envValues } from './dotenv.js';
5
+ import { DeployLockedError, describeHolder, readLock } from './lock.js';
6
+ import { createRunLog, newRunId, scanRunLog } from './runs.js';
7
+ /** The marker a detached child is started with; `--run-id` is refused without it. */
8
+ export const DETACHED_CHILD_ENV = 'BASALT_DEPLOY_DETACHED_CHILD';
9
+ /** How long the parent waits for the child to hold the lock. */
10
+ export const DETACH_CONFIRM_MS = 30_000;
11
+ const POLL_MS = 250;
12
+ /**
13
+ * `run --detach` / `rollback --detach` (RFC 0008 §8.2), the parent: it never
14
+ * takes the lock. Everything the child would need to ask is checked here
15
+ * first; the child is started in its own session with the answers on its
16
+ * stdin only; the parent returns once the child holds the lock.
17
+ */
18
+ export async function detach(ctx, request, reporter) {
19
+ const { host } = ctx;
20
+ if (!host.spawnDetached || !host.createLog)
21
+ throw new DeployError('this host cannot start a detached run', [], 'unsupported');
22
+ if (request.answers)
23
+ await request.answers.drain();
24
+ if (request.command === 'run')
25
+ await checkAnswers(ctx, request.answers);
26
+ // Advisory: the child's acquireLock decides; this only saves a pointless start.
27
+ const lock = await readLock(host, ctx.stateDir);
28
+ if (lock?.corrupt)
29
+ throw new DeployLockedError(`${lock.path} exists but is not a deploy lock (empty, unreadable or not a plain file) — if no deploy is running: rm ${lock.path}`);
30
+ if (lock?.holder && !lock.stale)
31
+ throw new DeployLockedError(`another deploy is running: ${describeHolder(lock.holder)} — wait for it`, lock.holder);
32
+ const runId = newRunId(host);
33
+ const { path, handle } = await createRunLog(host, ctx.stateDir, runId);
34
+ let pid;
35
+ try {
36
+ ;
37
+ ({ pid } = await host.spawnDetached(request.execPath, [request.binPath, request.command, '--json=1', `--run-id=${runId}`, ...request.forward], {
38
+ cwd: ctx.dir,
39
+ env: { ...host.env, [DETACHED_CHILD_ENV]: '1' },
40
+ stdin: request.answers?.serialize() ?? '',
41
+ stdout: handle,
42
+ }));
43
+ }
44
+ finally {
45
+ handle.close();
46
+ }
47
+ const deadline = host.now().getTime() + DETACH_CONFIRM_MS;
48
+ for (;;) {
49
+ const events = await scanRunLog(host, path);
50
+ const locked = events.find((e) => e.type === 'step-end' && e.id === 'lock');
51
+ if (locked?.status === 'ok') {
52
+ reporter.emit({ type: 'result', command: request.command, data: { runId, pid, log: path } });
53
+ return 0;
54
+ }
55
+ const done = events.find((e) => e.type === 'done');
56
+ if (done) {
57
+ const error = [...events].reverse().find((e) => e.type === 'error');
58
+ if (error) {
59
+ const { v: _v, ts: _ts, seq: _seq, runId: _run, redacted: _r, ...body } = error;
60
+ reporter.emit(body);
61
+ }
62
+ return done.exitCode;
63
+ }
64
+ if (host.now().getTime() >= deadline) {
65
+ throw new DeployError(`run ${runId} started (pid ${pid}) but did not confirm holding the lock within ${DETACH_CONFIRM_MS / 1000} s — it is not stopped`, [], 'detach-unconfirmed', `attach ${runId}`);
66
+ }
67
+ await host.sleep(POLL_MS);
68
+ }
69
+ }
70
+ /**
71
+ * Every question `run` would ask now is answered — by the deploy's own
72
+ * environment or by an answer line — and the answer can be written: a
73
+ * detached run cannot ask. Read-only: the `.env` as it is, no lock.
74
+ */
75
+ async function checkAnswers(ctx, answers) {
76
+ const document = await readEnv(ctx);
77
+ const values = envValues(document);
78
+ const plan = planEnv(ctx, document, Number(values.get('PORT')) || 0, []);
79
+ const missing = [];
80
+ for (const key of plan.questions) {
81
+ const question = ctx.config.env.ask?.[key];
82
+ if (!question || ctx.host.env[key] !== undefined)
83
+ continue;
84
+ const given = answers?.peek(`env.${key}`)?.trim();
85
+ if (given === undefined) {
86
+ if (!question.optional)
87
+ missing.push(key);
88
+ continue;
89
+ }
90
+ const value = given === '' && question.default !== undefined ? question.default : given;
91
+ if (value === '' && !question.optional)
92
+ throw new DeployError(`${key} is required: the answer is empty — nothing was started`, [], 'answer-invalid');
93
+ try {
94
+ formatValue(value, key);
95
+ }
96
+ catch (error) {
97
+ if (!(error instanceof UnwritableValueError))
98
+ throw error;
99
+ throw new DeployError(`${error.message} — nothing was started`, [], 'answer-invalid');
100
+ }
101
+ }
102
+ if (missing.length > 0) {
103
+ throw new DeployError(`a detached run cannot ask: no answer for ${missing.join(', ')} — nothing was started`, [], 'answer-missing', 'send them with --answers=stdin (plan --json lists them), or in the environment of the command');
104
+ }
105
+ }
@@ -1,5 +1,7 @@
1
+ import { type DeployConfig } from './config.js';
1
2
  import type { DeployContext, Finding } from './context.js';
2
3
  import { type EnvChange, type EnvDocument } from './dotenv.js';
4
+ import type { PromptDescriptor } from './protocol.js';
3
5
  /**
4
6
  * The `.env` step (RFC 0006 §6.1). Order: fixed → generated (only when absent)
5
7
  * → derived → infra → asked (only when absent) → forbidden removed.
@@ -26,11 +28,24 @@ export declare function planEnv(ctx: DeployContext, document: EnvDocument, port:
26
28
  * the deploy's own environment under the same name — CI, or a person who
27
29
  * prefers `MAILER_URL=… basalt-deploy run`. Returns what is still missing.
28
30
  */
29
- export declare function answerQuestions(ctx: DeployContext, plan: EnvPlan): Promise<string[]>;
31
+ export declare function answerQuestions(ctx: DeployContext, plan: EnvPlan, options?: {
32
+ secretsNeverDefault?: boolean;
33
+ }): Promise<string[]>;
34
+ /** The questions for `keys`, as a program sees them (`plan --json`): never a value, never a secret's default. */
35
+ export declare function questionDescriptors(config: DeployConfig, keys: string[]): PromptDescriptor[];
30
36
  export declare function describeEnv(plan: EnvPlan): string[];
31
37
  /** Backs the file up (0600, last 5 kept) and writes it atomically, 0600. */
32
38
  export declare function writeEnv(ctx: DeployContext, plan: EnvPlan): Promise<void>;
33
39
  /** Rewrites every mirror as an exact copy of the file (0600). */
34
40
  export declare function writeMirrors(ctx: DeployContext, text: string): Promise<void>;
41
+ /**
42
+ * The `.env` and its mirrors readable by anyone but their owner, or owned by
43
+ * someone else than the deploy user: the secrets are exposed, or the deploy
44
+ * cannot keep them 0600. `env` (and `run`) puts the mode right; an owner only
45
+ * root can change.
46
+ */
47
+ export declare function envModeFindings(ctx: DeployContext): Promise<Finding[]>;
48
+ /** Puts the `.env` and its mirrors back to 0600 when the deploy user owns them. Returns the files changed. */
49
+ export declare function secureEnvModes(ctx: DeployContext): Promise<string[]>;
35
50
  /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
36
51
  export declare function mirrorFindings(ctx: DeployContext): Promise<Finding[]>;
package/dist/env-step.js CHANGED
@@ -63,7 +63,7 @@ export function planEnv(ctx, document, port, infra) {
63
63
  * the deploy's own environment under the same name — CI, or a person who
64
64
  * prefers `MAILER_URL=… basalt-deploy run`. Returns what is still missing.
65
65
  */
66
- export async function answerQuestions(ctx, plan) {
66
+ export async function answerQuestions(ctx, plan, options = {}) {
67
67
  const missing = [];
68
68
  for (const key of plan.questions) {
69
69
  const question = ctx.config.env.ask?.[key];
@@ -71,7 +71,8 @@ export async function answerQuestions(ctx, plan) {
71
71
  continue;
72
72
  let answer = ctx.host.env[key]?.trim();
73
73
  for (let attempt = 0; answer === undefined && attempt < 3; attempt++) {
74
- const typed = await ctx.host.prompt(`${question.prompt} [${key}]${question.optional ? ' (empty to skip)' : ''}`, { secret: question.secret });
74
+ const meta = { id: `env.${key}`, key, optional: question.optional, ...(question.default === undefined ? {} : { default: question.default }) };
75
+ const typed = await ctx.host.prompt(promptText(key, question), { secret: question.secret }, meta);
75
76
  if (typed === undefined)
76
77
  break;
77
78
  const value = typed === '' && question.default !== undefined ? question.default : typed;
@@ -90,18 +91,35 @@ export async function answerQuestions(ctx, plan) {
90
91
  }
91
92
  }
92
93
  if (answer === undefined) {
93
- if (question.optional)
94
- answer = question.default ?? '';
95
- else {
94
+ if (!question.optional) {
96
95
  missing.push(key);
97
96
  continue;
98
97
  }
98
+ // A program's unanswered secret is never defaulted, not even to empty (RFC 0008 §7.3).
99
+ if (question.secret && options.secretsNeverDefault) {
100
+ ctx.host.out.warn(`${key} was not answered: left out of the .env`);
101
+ continue;
102
+ }
103
+ answer = question.default ?? '';
99
104
  }
100
105
  plan.changes.push({ kind: 'set', key, value: answer, reason: 'answered' });
101
106
  }
102
107
  plan.questions = [];
103
108
  return missing;
104
109
  }
110
+ const promptText = (key, question) => `${question.prompt} [${key}]${question.optional ? ' (empty to skip)' : ''}`;
111
+ /** The questions for `keys`, as a program sees them (`plan --json`): never a value, never a secret's default. */
112
+ export function questionDescriptors(config, keys) {
113
+ return keys.flatMap((key) => {
114
+ const question = config.env.ask?.[key];
115
+ if (!question)
116
+ return [];
117
+ return [{
118
+ id: `env.${key}`, kind: question.secret ? 'secret' : 'text', message: promptText(key, question), key, optional: question.optional,
119
+ ...(!question.secret && question.default !== undefined ? { default: question.default } : {}),
120
+ }];
121
+ });
122
+ }
105
123
  export function describeEnv(plan) {
106
124
  return [
107
125
  ...plan.changes.map((c) => c.kind === 'remove'
@@ -130,6 +148,9 @@ export async function writeEnv(ctx, plan) {
130
148
  await writeMirrors(ctx, text);
131
149
  plan.document = parseEnv(text);
132
150
  plan.values = envValues(plan.document);
151
+ // compose's passEnv reads ctx.values: it must see what was just written,
152
+ // not the .env before it (a recreated Redis left the worker on the old URL).
153
+ ctx.values = plan.values;
133
154
  plan.changes = [];
134
155
  }
135
156
  /** Rewrites every mirror as an exact copy of the file (0600). */
@@ -140,6 +161,41 @@ export async function writeMirrors(ctx, text) {
140
161
  await ctx.host.writeFile(mirror, text, 0o600);
141
162
  }
142
163
  }
164
+ /**
165
+ * The `.env` and its mirrors readable by anyone but their owner, or owned by
166
+ * someone else than the deploy user: the secrets are exposed, or the deploy
167
+ * cannot keep them 0600. `env` (and `run`) puts the mode right; an owner only
168
+ * root can change.
169
+ */
170
+ export async function envModeFindings(ctx) {
171
+ const findings = [];
172
+ const me = ctx.host.uid();
173
+ for (const file of [envFile(ctx), ...envMirrors(ctx)]) {
174
+ const stat = await ctx.host.stat(file);
175
+ if (stat?.kind !== 'file' || stat.mode === undefined)
176
+ continue;
177
+ if (stat.uid !== undefined && stat.uid !== me) {
178
+ findings.push({ id: 'env-owner', level: 'warning', message: `${file} is owned by uid ${stat.uid}, not by the deploy user (uid ${me})`, fix: `sudo chown "$USER": ${file} && chmod 600 ${file}` });
179
+ }
180
+ else if ((stat.mode & 0o077) !== 0) {
181
+ findings.push({ id: 'env-mode', level: 'warning', message: `${file} is ${(stat.mode & 0o777).toString(8).padStart(3, '0')}: its secrets are readable by other users of this server`, fix: 'this deploy sets it to 0600 (env and run do)' });
182
+ }
183
+ }
184
+ return findings;
185
+ }
186
+ /** Puts the `.env` and its mirrors back to 0600 when the deploy user owns them. Returns the files changed. */
187
+ export async function secureEnvModes(ctx) {
188
+ const fixed = [];
189
+ const me = ctx.host.uid();
190
+ for (const file of [envFile(ctx), ...envMirrors(ctx)]) {
191
+ const stat = await ctx.host.stat(file);
192
+ if (stat?.kind !== 'file' || stat.mode === undefined || stat.uid !== me || (stat.mode & 0o077) === 0)
193
+ continue;
194
+ await ctx.host.chmod(file, 0o600);
195
+ fixed.push(file);
196
+ }
197
+ return fixed;
198
+ }
143
199
  /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
144
200
  export async function mirrorFindings(ctx) {
145
201
  const mirrors = envMirrors(ctx);