@basaltkit/deploy 0.4.1 → 0.5.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 (53) hide show
  1. package/README.md +276 -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 +49 -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 +58 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +171 -7
  30. package/dist/host.js +302 -41
  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 +433 -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/host.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { Finding } from './context.js';
2
+ import type { ResultCommand, ResultPayloads, StepId, StepStatus } from './protocol.js';
1
3
  /**
2
4
  * Every side effect the pipeline has goes through this interface: processes,
3
5
  * files, the terminal, the network, the clock. The real one is {@link nodeHost};
@@ -11,19 +13,48 @@ export interface Host {
11
13
  writeFile(path: string, content: string, mode?: number): Promise<void>;
12
14
  copyFile(from: string, to: string, mode?: number): Promise<void>;
13
15
  exists(path: string): Promise<boolean>;
14
- stat(path: string): Promise<{
15
- kind: 'file' | 'dir' | 'symlink' | 'other';
16
- size: number;
17
- } | undefined>;
16
+ /** lstat: a symlink is reported as one, never followed. */
17
+ stat(path: string): Promise<FileStat | undefined>;
18
+ chmod(path: string, mode: number): Promise<void>;
19
+ /** The path with every symlink resolved, or `undefined` when it does not exist. */
20
+ realpath(path: string): Promise<string | undefined>;
21
+ /**
22
+ * Reads a regular file without following a symlink at `path` (O_NOFOLLOW),
23
+ * up to `maxBytes`. Throws for a link, a non-regular file or a larger one —
24
+ * how root reads a file the app user wrote.
25
+ */
26
+ readPlainFile(path: string, maxBytes: number): Promise<string>;
27
+ /**
28
+ * Gives `path` to `uid:gid` with `mode`, through a descriptor opened with
29
+ * O_NOFOLLOW: a symlink planted at `path` is refused, never followed; a file
30
+ * with more than one hard link too. How root changes a file in a directory
31
+ * the app user can write.
32
+ */
33
+ secureOwner(path: string, owner: {
34
+ uid: number;
35
+ gid: number;
36
+ mode: number;
37
+ kind: 'file' | 'dir';
38
+ }): Promise<void>;
18
39
  readlink(path: string): Promise<string | undefined>;
19
40
  symlink(target: string, path: string): Promise<void>;
20
41
  mkdir(path: string, mode?: number): Promise<void>;
42
+ /** Recursive and forced (`rm -rf`): never as root under a directory another user can write. */
21
43
  remove(path: string): Promise<void>;
44
+ /**
45
+ * unlink(2) of one entry: a file, or a symlink itself (never its target);
46
+ * a directory is an error, never descended into. Nothing there is fine.
47
+ */
48
+ removeFile(path: string): Promise<void>;
22
49
  list(dir: string): Promise<string[]>;
23
- /** A line typed by a person, or `undefined` when nobody can answer (no TTY). */
50
+ /**
51
+ * A line typed by a person, or `undefined` when nobody can answer (no TTY).
52
+ * `meta` names the question for a program answering it (RFC 0008 §7.2);
53
+ * the terminal ignores it.
54
+ */
24
55
  prompt(question: string, options: {
25
56
  secret: boolean;
26
- }): Promise<string | undefined>;
57
+ }, meta?: PromptMeta): Promise<string | undefined>;
27
58
  confirm(question: string): Promise<boolean>;
28
59
  randomHex(bytes: number): string;
29
60
  now(): Date;
@@ -46,7 +77,93 @@ export interface Host {
46
77
  /** Whether a person can answer a prompt (a terminal, not CI). */
47
78
  interactive(): boolean;
48
79
  uid(): number;
80
+ /** This process's id (recorded in the deploy lock). */
81
+ pid(): number;
82
+ hostname(): string;
83
+ /** Whether a process with this id runs on this host (a stale lock's holder does not). */
84
+ processAlive(pid: number): boolean;
85
+ /**
86
+ * Creates `path` with `content` only when nothing is there — O_EXCL, so a
87
+ * symlink planted at `path` is not followed. `false` when it already exists.
88
+ */
89
+ createExclusive(path: string, content: string, mode: number): Promise<boolean>;
90
+ /**
91
+ * SIGINT, SIGTERM and SIGHUP while a deploy runs: the listener hears the
92
+ * first; a second one ends the process at once — and, when the deploy
93
+ * leads its own process group (a detached run always does), SIGTERM goes
94
+ * to that group first, so the step's child never outlives the deploy that
95
+ * held the lock. `second` says so in place of the default line on the
96
+ * terminal. Returns the unsubscribe.
97
+ */
98
+ onSignal(listener: (signal: string) => void, options?: {
99
+ second?: (signal: string) => void;
100
+ }): () => void;
49
101
  out: Output;
102
+ /**
103
+ * Creates `path` for appending — O_CREAT|O_EXCL|O_NOFOLLOW, `mode` — and
104
+ * returns a handle: a run log. Something already there (a planted symlink
105
+ * included) is an error, never followed or reused.
106
+ */
107
+ createLog?(path: string, mode: number): Promise<LogHandle>;
108
+ /**
109
+ * Up to `length` bytes of `path` from `offset`, read through a descriptor
110
+ * opened with O_NOFOLLOW, with what fstat says of that file. Throws for a
111
+ * symlink or a non-regular file.
112
+ */
113
+ readFileRange?(path: string, offset: number, length: number): Promise<FileRange>;
114
+ /**
115
+ * Starts `command` in its own session (setsid: no controlling terminal, no
116
+ * SIGHUP when the SSH session ends), stdin a pipe that receives `stdin` and
117
+ * is closed, stdout the log handle, stderr /dev/null; not waited for.
118
+ */
119
+ spawnDetached?(command: string, args: string[], options: {
120
+ cwd: string;
121
+ env: Record<string, string | undefined>;
122
+ stdin: string;
123
+ stdout: LogHandle;
124
+ }): Promise<{
125
+ pid: number;
126
+ }>;
127
+ /** kill(2) of one process (never its group). */
128
+ kill?(pid: number, signal: 'SIGTERM'): void;
129
+ /**
130
+ * Whether a process group with this id still has a process in it. A dead
131
+ * detached run's group (its id is the run's pid) with a process left is a
132
+ * step's child still working on the checkout: its lock is not stale.
133
+ */
134
+ processGroupAlive?(pgid: number): boolean;
135
+ /** The process's argv (Linux /proc/<pid>/cmdline), or `undefined` when it cannot be known. */
136
+ processCmdline?(pid: number): Promise<string[] | undefined>;
137
+ }
138
+ /** Who a prompt is for, for a program that answers it (RFC 0008 §7.2). */
139
+ export interface PromptMeta {
140
+ /** `env.<KEY>`. */
141
+ id: string;
142
+ key: string;
143
+ optional: boolean;
144
+ default?: string;
145
+ }
146
+ export interface LogHandle {
147
+ append(text: string): void;
148
+ close(): void;
149
+ /** The descriptor, for a detached child's stdout. */
150
+ readonly fd?: number;
151
+ }
152
+ export interface FileRange {
153
+ data: Uint8Array;
154
+ /** The whole file's size. */
155
+ size: number;
156
+ uid: number;
157
+ /** Permission bits. */
158
+ mode: number;
159
+ }
160
+ export interface FileStat {
161
+ kind: 'file' | 'dir' | 'symlink' | 'other';
162
+ size: number;
163
+ /** Permission bits (`& 0o7777`). */
164
+ mode?: number;
165
+ uid?: number;
166
+ gid?: number;
50
167
  }
51
168
  export interface ExecOptions {
52
169
  cwd?: string;
@@ -62,6 +179,13 @@ export interface ExecOptions {
62
179
  stream?: boolean;
63
180
  /** Written to the child's stdin, then closed — SQL that carries a password, never an argument. */
64
181
  stdin?: string;
182
+ /** The child gets this terminal (stdin too): it may ask questions. Nothing is captured. */
183
+ interactive?: boolean;
184
+ /**
185
+ * With `stream`: stdout/stderr are piped (stdin stays closed) and handed
186
+ * here as decoded text, instead of going to the terminal (RFC 0008 §5.3).
187
+ */
188
+ onOutput?: (text: string, stream: 'stdout' | 'stderr') => void;
65
189
  }
66
190
  export interface ExecResult {
67
191
  code: number;
@@ -77,13 +201,53 @@ export interface TlsCertificate {
77
201
  trustError?: string;
78
202
  }
79
203
  export interface Output {
80
- step(title: string): void;
204
+ /** A step begins; `id` names it for a program (the terminal shows the title). */
205
+ step(title: string, id?: StepId): void;
81
206
  info(message: string): void;
82
207
  ok(message: string): void;
83
208
  warn(message: string): void;
84
209
  error(message: string): void;
210
+ /** The step `id` ended. */
211
+ stepEnd?(id: StepId, status: StepStatus, durationMs: number): void;
212
+ /** A finding, structured (the terminal gets it as text). */
213
+ finding?(finding: Finding): void;
214
+ /** The command's payload. */
215
+ result?<C extends ResultCommand>(command: C, data: ResultPayloads[C]): void;
85
216
  }
86
217
  export declare function consoleOutput(stream?: NodeJS.WriteStream): Output;
218
+ /** How long a piped child's output may keep arriving after it exited (its pipes held by a process it left behind). */
219
+ export declare const PIPE_GRACE_MS = 1500;
220
+ /** What a second signal says before the deploy stops. */
221
+ export declare const secondSignalMessage: (signal: string) => string;
222
+ /**
223
+ * SIGTERM to this process's group, when this process leads one (a detached
224
+ * run: setsid; a command started from a shell). `kill(-pid, 0)` fails with
225
+ * ESRCH when no group has this pid as its id, i.e. when it is not a leader:
226
+ * then nothing is sent — a deploy started by another program never signals
227
+ * that program's group.
228
+ */
229
+ export declare function stopOwnGroup(pid?: number, kill?: (pid: number, signal: NodeJS.Signals | 0) => void): boolean;
87
230
  export declare function nodeHost(output?: Output): Host;
231
+ /**
232
+ * Readline echoes what is typed through its internal `_writeToOutput`; a
233
+ * secret answer replaces it so only the question is written. Returns false
234
+ * when that internal is gone (a Node that changed it): the caller must not
235
+ * ask then — fail closed, never echo a secret.
236
+ */
237
+ export declare function muteEcho(rl: unknown, write: (text: string) => void): boolean;
238
+ /**
239
+ * The certificate `host:port` presents for `servername`. The chain is
240
+ * verified as any client would (the system's roots), but an untrusted or
241
+ * expired one is REPORTED, with its names and expiry, instead of failing the
242
+ * handshake — what C8 says to the operator. Only network failures are
243
+ * errors. Nothing is sent over the connection.
244
+ */
245
+ export declare function probeTls(servername: string, target: {
246
+ host: string;
247
+ port: number;
248
+ timeoutMs?: number;
249
+ }): Promise<TlsCertificate | {
250
+ error: string;
251
+ }>;
88
252
  /** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
89
253
  export declare const parentOf: (path: string) => string;
package/dist/host.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomBytes } from 'node:crypto';
3
- import { constants, openSync, closeSync } from 'node:fs';
4
- import { chmod, copyFile, lstat, mkdir, readFile, readdir, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { constants, openSync, closeSync, writeSync } from 'node:fs';
4
+ import { chmod, copyFile, lstat, mkdir, open, readFile, readdir, readlink, realpath, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';
5
5
  import http from 'node:http';
6
6
  import https from 'node:https';
7
+ import { hostname } from 'node:os';
7
8
  import { dirname } from 'node:path';
8
9
  import { createInterface } from 'node:readline';
10
+ import { StringDecoder } from 'node:string_decoder';
9
11
  import tls from 'node:tls';
10
12
  export function consoleOutput(stream = process.stderr) {
11
13
  const color = stream.isTTY && !process.env['NO_COLOR'];
@@ -18,11 +20,84 @@ export function consoleOutput(stream = process.stderr) {
18
20
  error: (message) => stream.write(` ${paint('31', 'error')} ${message}\n`),
19
21
  };
20
22
  }
23
+ /** How long a piped child's output may keep arriving after it exited (its pipes held by a process it left behind). */
24
+ export const PIPE_GRACE_MS = 1500;
25
+ /** What a second signal says before the deploy stops. */
26
+ export const secondSignalMessage = (signal) => `${signal} again: stopping now, mid-step — the step's processes are stopped too; the lock is cleared by the next deploy once they are gone`;
27
+ /**
28
+ * SIGTERM to this process's group, when this process leads one (a detached
29
+ * run: setsid; a command started from a shell). `kill(-pid, 0)` fails with
30
+ * ESRCH when no group has this pid as its id, i.e. when it is not a leader:
31
+ * then nothing is sent — a deploy started by another program never signals
32
+ * that program's group.
33
+ */
34
+ export function stopOwnGroup(pid = process.pid, kill = (p, s) => { process.kill(p, s); }) {
35
+ try {
36
+ kill(-pid, 0);
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ try {
42
+ kill(-pid, 'SIGTERM');
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
21
49
  export function nodeHost(output = consoleOutput()) {
22
50
  return {
23
51
  out: output,
24
52
  env: process.env,
25
53
  uid: () => (typeof process.getuid === 'function' ? process.getuid() : -1),
54
+ pid: () => process.pid,
55
+ hostname: () => hostname(),
56
+ processAlive(pid) {
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ }
61
+ catch (error) {
62
+ // EPERM: it exists, under another user.
63
+ return error.code === 'EPERM';
64
+ }
65
+ },
66
+ async createExclusive(path, content, mode) {
67
+ try {
68
+ await writeFile(path, content, { mode, flag: 'wx' });
69
+ return true;
70
+ }
71
+ catch (error) {
72
+ if (error.code === 'EEXIST')
73
+ return false;
74
+ throw error;
75
+ }
76
+ },
77
+ onSignal(listener, options = {}) {
78
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
79
+ let heard = 0;
80
+ const handler = (signal) => {
81
+ heard++;
82
+ if (heard === 1) {
83
+ listener(signal);
84
+ return;
85
+ }
86
+ // Our own SIGTERM to the group below comes back here: already stopping.
87
+ if (heard > 2)
88
+ return;
89
+ if (options.second)
90
+ options.second(signal);
91
+ else
92
+ output.error(secondSignalMessage(signal));
93
+ stopOwnGroup();
94
+ process.exit(signal === 'SIGINT' ? 130 : signal === 'SIGHUP' ? 129 : 143);
95
+ };
96
+ for (const signal of SIGNALS)
97
+ process.on(signal, handler);
98
+ return () => { for (const signal of SIGNALS)
99
+ process.off(signal, handler); };
100
+ },
26
101
  interactive: () => Boolean(process.stdin.isTTY) && !process.env['CI'],
27
102
  now: () => new Date(),
28
103
  randomHex: (bytes) => randomBytes(bytes).toString('hex'),
@@ -41,22 +116,54 @@ export function nodeHost(output = consoleOutput()) {
41
116
  return new Promise((resolve) => {
42
117
  let stdout = '';
43
118
  let stderr = '';
119
+ const sink = options.stream ? options.onOutput : undefined;
44
120
  const child = spawn(command, args, {
45
121
  cwd: options.cwd,
46
122
  env,
47
- stdio: options.stream ? ['ignore', 'inherit', 'inherit'] : [options.stdin === undefined ? 'ignore' : 'pipe', fd ?? 'pipe', 'pipe'],
123
+ stdio: options.interactive ? 'inherit'
124
+ : sink ? ['ignore', 'pipe', 'pipe']
125
+ : options.stream ? ['ignore', 'inherit', 'inherit']
126
+ : [options.stdin === undefined ? 'ignore' : 'pipe', fd ?? 'pipe', 'pipe'],
48
127
  });
49
128
  if (options.stdin !== undefined)
50
129
  child.stdin?.end(options.stdin);
51
- child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
52
- child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
130
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
131
+ if (sink) {
132
+ child.stdout?.on('data', (chunk) => sink(decoders.stdout.write(chunk), 'stdout'));
133
+ child.stderr?.on('data', (chunk) => sink(decoders.stderr.write(chunk), 'stderr'));
134
+ }
135
+ else {
136
+ child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
137
+ child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
138
+ }
139
+ let finished = false;
53
140
  const done = (code) => {
141
+ if (finished)
142
+ return;
143
+ finished = true;
54
144
  if (fd !== undefined)
55
145
  closeSync(fd);
146
+ if (sink) {
147
+ // A process the child left behind may still hold the pipes: stop reading them.
148
+ child.stdout?.destroy();
149
+ child.stderr?.destroy();
150
+ sink(decoders.stdout.end(), 'stdout');
151
+ sink(decoders.stderr.end(), 'stderr');
152
+ }
56
153
  resolve({ code, stdout, stderr });
57
154
  };
58
155
  child.on('error', (error) => { stderr += error.message; done(127); });
59
156
  child.on('close', (code) => done(code ?? 1));
157
+ if (sink) {
158
+ // Piped (--json), 'close' waits for every holder of the pipes — a
159
+ // background process a hook or a build started would hold the deploy
160
+ // (and its lock) forever, where the terminal's inherited stdio would
161
+ // not. The child's exit ends it; what it wrote just before still
162
+ // arrives within the grace period.
163
+ child.on('exit', (code) => {
164
+ setTimeout(() => done(code ?? 1), PIPE_GRACE_MS);
165
+ });
166
+ }
60
167
  });
61
168
  },
62
169
  async readFile(path) {
@@ -91,7 +198,7 @@ export function nodeHost(output = consoleOutput()) {
91
198
  try {
92
199
  const s = await lstat(path);
93
200
  const kind = s.isSymbolicLink() ? 'symlink' : s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other';
94
- return { kind, size: s.size };
201
+ return { kind, size: s.size, mode: s.mode & 0o7777, uid: s.uid, gid: s.gid };
95
202
  }
96
203
  catch {
97
204
  return undefined;
@@ -106,10 +213,60 @@ export function nodeHost(output = consoleOutput()) {
106
213
  }
107
214
  },
108
215
  symlink: (target, path) => symlink(target, path),
216
+ chmod: (path, mode) => chmod(path, mode),
217
+ async realpath(path) {
218
+ try {
219
+ return await realpath(path);
220
+ }
221
+ catch {
222
+ return undefined;
223
+ }
224
+ },
225
+ async readPlainFile(path, maxBytes) {
226
+ const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK);
227
+ try {
228
+ const s = await handle.stat();
229
+ if (!s.isFile())
230
+ throw new Error(`${path} is not a regular file`);
231
+ if (s.size > maxBytes)
232
+ throw new Error(`${path} is larger than ${maxBytes} bytes`);
233
+ return await handle.readFile('utf8');
234
+ }
235
+ finally {
236
+ await handle.close();
237
+ }
238
+ },
239
+ async secureOwner(path, { uid, gid, mode, kind }) {
240
+ const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK | (kind === 'dir' ? constants.O_DIRECTORY : 0));
241
+ try {
242
+ const s = await handle.stat();
243
+ if (kind === 'file' && !s.isFile())
244
+ throw new Error(`${path} is not a regular file`);
245
+ if (kind === 'dir' && !s.isDirectory())
246
+ throw new Error(`${path} is not a directory`);
247
+ // A hard link to another file (a password file, say) would change that file too.
248
+ if (kind === 'file' && s.nlink !== 1)
249
+ throw new Error(`${path} has ${s.nlink} hard links`);
250
+ await handle.chown(uid, gid);
251
+ await handle.chmod(mode);
252
+ }
253
+ finally {
254
+ await handle.close();
255
+ }
256
+ },
109
257
  async mkdir(path, mode) {
110
258
  await mkdir(path, { recursive: true, ...(mode === undefined ? {} : { mode }) });
111
259
  },
112
260
  remove: (path) => rm(path, { force: true, recursive: true }),
261
+ async removeFile(path) {
262
+ try {
263
+ await unlink(path);
264
+ }
265
+ catch (error) {
266
+ if (error.code !== 'ENOENT')
267
+ throw error;
268
+ }
269
+ },
113
270
  async list(dir) {
114
271
  try {
115
272
  return await readdir(dir);
@@ -124,15 +281,11 @@ export function nodeHost(output = consoleOutput()) {
124
281
  // The question and the echo go to stderr: anything a prompt writes to
125
282
  // stdout can end up inside a captured value (RFC 0006 §A, incident 5).
126
283
  const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
127
- if (secret) {
128
- const writer = rl;
129
- let asked = false;
130
- writer._writeToOutput = (s) => {
131
- if (!asked) {
132
- process.stderr.write(s);
133
- asked = true;
134
- }
135
- };
284
+ if (secret && !muteEcho(rl, (s) => process.stderr.write(s))) {
285
+ // Fail closed: never ask for a secret that would be echoed.
286
+ rl.close();
287
+ output.warn('this Node cannot hide what is typed: give the secret in the environment of the command instead');
288
+ return undefined;
136
289
  }
137
290
  const answer = await new Promise((resolve) => rl.question(` ${question}: `, resolve));
138
291
  rl.close();
@@ -148,36 +301,80 @@ export function nodeHost(output = consoleOutput()) {
148
301
  rl.close();
149
302
  return /^y(es)?$/i.test(answer.trim());
150
303
  },
151
- tlsCertificate(servername) {
152
- return new Promise((resolve) => {
153
- // The chain is verified as for any client: an untrusted or expired
154
- // certificate fails the handshake and is reported by its code. Only
155
- // the NAME check is ours — it records the certificate instead of
156
- // refusing it, because which names it covers is what we report (C8).
157
- // Nothing is sent over the connection either way.
158
- let names = [];
159
- const socket = tls.connect({
160
- host: servername, port: 443, servername, timeout: 10_000,
161
- checkServerIdentity: (_host, cert) => {
162
- names = (cert.subjectaltname ?? '')
163
- .split(',')
164
- .map((entry) => entry.trim())
165
- .filter((entry) => entry.startsWith('DNS:'))
166
- .map((entry) => entry.slice(4).toLowerCase());
167
- return undefined;
168
- },
169
- });
170
- const finish = (value) => { socket.destroy(); resolve(value); };
171
- socket.once('secureConnect', () => {
172
- finish({ names, validTo: new Date(socket.getPeerCertificate().valid_to), trusted: true });
304
+ tlsCertificate: (servername) => probeTls(servername, { host: servername, port: 443 }),
305
+ async createLog(path, mode) {
306
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_APPEND, mode);
307
+ return {
308
+ fd,
309
+ append(text) {
310
+ const bytes = Buffer.from(text, 'utf8');
311
+ for (let written = 0; written < bytes.length;)
312
+ written += writeSync(fd, bytes, written);
313
+ },
314
+ close() { closeSync(fd); },
315
+ };
316
+ },
317
+ async readFileRange(path, offset, length) {
318
+ const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK);
319
+ try {
320
+ const s = await handle.stat();
321
+ if (!s.isFile())
322
+ throw new Error(`${path} is not a regular file`);
323
+ const data = Buffer.alloc(Math.max(0, Math.min(length, s.size - offset)));
324
+ let read = 0;
325
+ while (read < data.length) {
326
+ const { bytesRead } = await handle.read(data, read, data.length - read, offset + read);
327
+ if (bytesRead === 0)
328
+ break;
329
+ read += bytesRead;
330
+ }
331
+ return { data: data.subarray(0, read), size: s.size, uid: s.uid, mode: s.mode & 0o7777 };
332
+ }
333
+ finally {
334
+ await handle.close();
335
+ }
336
+ },
337
+ spawnDetached(command, args, options) {
338
+ return new Promise((resolve, reject) => {
339
+ if (options.stdout.fd === undefined) {
340
+ reject(new Error('the run log has no descriptor'));
341
+ return;
342
+ }
343
+ const child = spawn(command, args, {
344
+ cwd: options.cwd,
345
+ env: options.env,
346
+ // setsid(2): its own session and process group, no controlling terminal.
347
+ detached: true,
348
+ stdio: ['pipe', options.stdout.fd, 'ignore'],
173
349
  });
174
- socket.once('timeout', () => finish({ error: 'timed out' }));
175
- socket.once('error', (error) => {
176
- const code = error.code ?? '';
177
- finish({ error: /CERT|SELF_SIGNED|UNABLE_TO|VERIFY/.test(code) ? `certificate not trusted by browsers (${code})` : error.message });
350
+ child.once('error', reject);
351
+ child.once('spawn', () => {
352
+ child.stdin?.end(options.stdin);
353
+ child.unref();
354
+ resolve({ pid: child.pid });
178
355
  });
179
356
  });
180
357
  },
358
+ kill(pid, signal) { process.kill(pid, signal); },
359
+ processGroupAlive(pgid) {
360
+ try {
361
+ process.kill(-pgid, 0);
362
+ return true;
363
+ }
364
+ catch (error) {
365
+ return error.code === 'EPERM';
366
+ }
367
+ },
368
+ async processCmdline(pid) {
369
+ if (process.platform !== 'linux')
370
+ return undefined;
371
+ try {
372
+ return (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\u0000').filter(Boolean);
373
+ }
374
+ catch {
375
+ return undefined;
376
+ }
377
+ },
181
378
  httpGet(url, options = {}) {
182
379
  return new Promise((resolve) => {
183
380
  const target = new URL(url);
@@ -197,5 +394,69 @@ export function nodeHost(output = consoleOutput()) {
197
394
  },
198
395
  };
199
396
  }
397
+ /**
398
+ * Readline echoes what is typed through its internal `_writeToOutput`; a
399
+ * secret answer replaces it so only the question is written. Returns false
400
+ * when that internal is gone (a Node that changed it): the caller must not
401
+ * ask then — fail closed, never echo a secret.
402
+ */
403
+ export function muteEcho(rl, write) {
404
+ const writer = rl;
405
+ if (typeof writer._writeToOutput !== 'function')
406
+ return false;
407
+ let asked = false;
408
+ writer._writeToOutput = (text) => {
409
+ if (!asked) {
410
+ write(text);
411
+ asked = true;
412
+ }
413
+ };
414
+ return true;
415
+ }
416
+ /**
417
+ * The certificate `host:port` presents for `servername`. The chain is
418
+ * verified as any client would (the system's roots), but an untrusted or
419
+ * expired one is REPORTED, with its names and expiry, instead of failing the
420
+ * handshake — what C8 says to the operator. Only network failures are
421
+ * errors. Nothing is sent over the connection.
422
+ */
423
+ export function probeTls(servername, target) {
424
+ return new Promise((resolve) => {
425
+ const socket = tls.connect({
426
+ host: target.host, port: target.port, servername, timeout: target.timeoutMs ?? 10_000,
427
+ // Reported, not refused: `authorized` says whether the chain verifies.
428
+ rejectUnauthorized: false,
429
+ // The name check is ours (covers()): a name mismatch is not a trust error.
430
+ checkServerIdentity: () => undefined,
431
+ });
432
+ const finish = (value) => { socket.destroy(); resolve(value); };
433
+ socket.once('secureConnect', () => {
434
+ const cert = socket.getPeerCertificate();
435
+ const names = (cert.subjectaltname ?? '')
436
+ .split(',')
437
+ .map((entry) => entry.trim())
438
+ .filter((entry) => entry.startsWith('DNS:'))
439
+ .map((entry) => entry.slice(4).toLowerCase());
440
+ const trustError = socket.authorized ? undefined : String(socket.authorizationError ?? 'unknown');
441
+ finish({ names, validTo: new Date(cert.valid_to), trusted: socket.authorized, ...(trustError ? { trustError } : {}) });
442
+ });
443
+ socket.once('timeout', () => finish({ error: 'timed out' }));
444
+ socket.once('error', (error) => finish({ error: error.message }));
445
+ });
446
+ }
447
+ /** open(2) with O_NOFOLLOW: a symlink at `path` is an error that says so. */
448
+ async function openNoFollow(path, flags) {
449
+ try {
450
+ return await open(path, flags | constants.O_NOFOLLOW);
451
+ }
452
+ catch (error) {
453
+ const code = error.code;
454
+ if (code === 'ELOOP' || code === 'EMLINK')
455
+ throw new Error(`${path} is a symbolic link — refused, never followed`);
456
+ if (code === 'ENOTDIR')
457
+ throw new Error(`${path} is not a directory`);
458
+ throw error;
459
+ }
460
+ }
200
461
  /** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
201
462
  export const parentOf = (path) => dirname(path);
package/dist/index.d.ts CHANGED
@@ -1,11 +1,16 @@
1
1
  export { defineDeploy, secret, ask, pm2, compose, apache, caddy, none, external, bucketName, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvShape, type EnvKey, type EnvValue, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type ExternalPostgres, type AppRole, type Bucket, type VerifyConfig, type ComposeJob, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ComposeRuntime, type ComposeImage, type HooksConfig, type ProxyConfig, type ApacheProxy, type CaddyProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
2
- export { main, loadConfig, createContext, USAGE } from './cli.js';
3
- export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type Output, type TlsCertificate } from './host.js';
4
- export { DeployError, INSTALL_COMMAND, RUN_COMMAND, type DeployContext, type Finding } from './context.js';
2
+ export { main, loadConfig, createContext, processIO, USAGE, type CliIO } from './cli.js';
3
+ export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type FileStat, type Output, type TlsCertificate, type PromptMeta, type LogHandle, type FileRange } from './host.js';
4
+ export { DeployAbortedError, DeployError, INSTALL_COMMAND, RUN_COMMAND, rootInstallCommand, type DeployContext, type Finding } from './context.js';
5
5
  export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError, type EnvDocument, type EnvChange } from './dotenv.js';
6
6
  export { renderVhost, proxiedPorts } from './apache.js';
7
7
  export { renderCompose } from './infra.js';
8
8
  export { coercionFindings } from './env-check.js';
9
9
  export { covers } from './checks.js';
10
- export { plan, run, envCommand, rollback, status, install, preflight, SKIPPABLE, type Skippable, type RunOptions } from './pipeline.js';
11
- export type { Release } from './state.js';
10
+ export { plan, run, envCommand, rollback, status, preflight, refuseRoot, SKIPPABLE, type Skippable, type RunOptions, type ProtocolHooks } from './pipeline.js';
11
+ export { install, buildInstallPlan, parseInstallPlan, readInstallPlan, type InstallPlan, type InstallOptions, type PlanProxy } from './install-plan.js';
12
+ export { DeployLockedError, type LockHolder } from './lock.js';
13
+ export { EXIT_ABORTED, EXIT_LOCKED } from './cli.js';
14
+ export type { Hold, Release } from './state.js';
15
+ export type { Audit } from './audit.js';
16
+ export { parseEvent, parseAnswerLine, PROTOCOL_VERSION, STEP_IDS, ERROR_CODES, EVENT_TYPES, RUN_ID, type DeployEvent, type EventBody, type EventType, type Envelope, type HelloEvent, type StepStartEvent, type StepEndEvent, type LogEvent, type FindingEvent, type PromptEvent, type PromptDescriptor, type ResultEvent, type ErrorEvent, type DoneEvent, type AttachedEvent, type StepId, type StepStatus, type ErrorCode, type AnswerLine, type StatusResult, type CheckResult, type PlanResult, type RunResult, type RollbackResult, type EnvResult, type DetachResult, type CancelResult, type InstallPlanResult, } from './protocol.js';