@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.
- package/README.md +284 -23
- package/dist/answers.d.ts +70 -0
- package/dist/answers.js +196 -0
- package/dist/apache.js +11 -2
- package/dist/audit.d.ts +20 -0
- package/dist/audit.js +26 -0
- package/dist/backup.d.ts +17 -1
- package/dist/backup.js +56 -1
- package/dist/bin.js +9 -1
- package/dist/bootstrap.d.ts +68 -18
- package/dist/bootstrap.js +177 -45
- package/dist/caddy.js +2 -1
- package/dist/check.js +18 -5
- package/dist/checks.js +1 -1
- package/dist/cli.d.ts +22 -1
- package/dist/cli.js +498 -57
- package/dist/compose.d.ts +1 -1
- package/dist/compose.js +6 -1
- package/dist/config.d.ts +25 -2
- package/dist/config.js +65 -3
- package/dist/context.d.ts +43 -13
- package/dist/context.js +50 -7
- package/dist/detach.d.ts +23 -0
- package/dist/detach.js +105 -0
- package/dist/env-step.d.ts +16 -1
- package/dist/env-step.js +61 -5
- package/dist/events.d.ts +168 -0
- package/dist/events.js +477 -0
- package/dist/host.d.ts +179 -7
- package/dist/host.js +317 -42
- package/dist/index.d.ts +10 -5
- package/dist/index.js +7 -3
- package/dist/init.d.ts +2 -0
- package/dist/init.js +2 -1
- package/dist/install-plan.d.ts +40 -0
- package/dist/install-plan.js +437 -0
- package/dist/json-host.d.ts +32 -0
- package/dist/json-host.js +106 -0
- package/dist/lock.d.ts +45 -0
- package/dist/lock.js +128 -0
- package/dist/pipeline.d.ts +51 -3
- package/dist/pipeline.js +339 -173
- package/dist/protocol.d.ts +364 -0
- package/dist/protocol.js +134 -0
- package/dist/runs.d.ts +75 -0
- package/dist/runs.js +287 -0
- package/dist/state.d.ts +26 -13
- package/dist/state.js +68 -4
- package/dist/trust.d.ts +63 -0
- package/dist/trust.js +159 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- 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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
/**
|
|
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,61 @@ export interface TlsCertificate {
|
|
|
77
201
|
trustError?: string;
|
|
78
202
|
}
|
|
79
203
|
export interface Output {
|
|
80
|
-
step(title
|
|
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;
|
|
230
|
+
/**
|
|
231
|
+
* `PATH` with the directory of the node running the deploy first. A version
|
|
232
|
+
* manager (nvm, fnm, volta) puts node and its pnpm/corepack shims on `PATH`
|
|
233
|
+
* only in an interactive shell, so over `ssh host cmd`, in cron or under the
|
|
234
|
+
* local UI the children (`pnpm`, `node`) would not be found, or would be
|
|
235
|
+
* another node than the one the deploy runs on.
|
|
236
|
+
*/
|
|
237
|
+
export declare function withOwnNode(path: string | undefined, execPath: string): string;
|
|
87
238
|
export declare function nodeHost(output?: Output): Host;
|
|
239
|
+
/**
|
|
240
|
+
* Readline echoes what is typed through its internal `_writeToOutput`; a
|
|
241
|
+
* secret answer replaces it so only the question is written. Returns false
|
|
242
|
+
* when that internal is gone (a Node that changed it): the caller must not
|
|
243
|
+
* ask then — fail closed, never echo a secret.
|
|
244
|
+
*/
|
|
245
|
+
export declare function muteEcho(rl: unknown, write: (text: string) => void): boolean;
|
|
246
|
+
/**
|
|
247
|
+
* The certificate `host:port` presents for `servername`. The chain is
|
|
248
|
+
* verified as any client would (the system's roots), but an untrusted or
|
|
249
|
+
* expired one is REPORTED, with its names and expiry, instead of failing the
|
|
250
|
+
* handshake — what C8 says to the operator. Only network failures are
|
|
251
|
+
* errors. Nothing is sent over the connection.
|
|
252
|
+
*/
|
|
253
|
+
export declare function probeTls(servername: string, target: {
|
|
254
|
+
host: string;
|
|
255
|
+
port: number;
|
|
256
|
+
timeoutMs?: number;
|
|
257
|
+
}): Promise<TlsCertificate | {
|
|
258
|
+
error: string;
|
|
259
|
+
}>;
|
|
88
260
|
/** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
|
|
89
261
|
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 {
|
|
7
|
+
import { hostname } from 'node:os';
|
|
8
|
+
import { delimiter, 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,96 @@ 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
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* `PATH` with the directory of the node running the deploy first. A version
|
|
51
|
+
* manager (nvm, fnm, volta) puts node and its pnpm/corepack shims on `PATH`
|
|
52
|
+
* only in an interactive shell, so over `ssh host cmd`, in cron or under the
|
|
53
|
+
* local UI the children (`pnpm`, `node`) would not be found, or would be
|
|
54
|
+
* another node than the one the deploy runs on.
|
|
55
|
+
*/
|
|
56
|
+
export function withOwnNode(path, execPath) {
|
|
57
|
+
const own = dirname(execPath);
|
|
58
|
+
const entries = (path ?? '').split(delimiter).filter((entry) => entry !== '' && entry !== own);
|
|
59
|
+
return [own, ...entries].join(delimiter);
|
|
60
|
+
}
|
|
21
61
|
export function nodeHost(output = consoleOutput()) {
|
|
22
62
|
return {
|
|
23
63
|
out: output,
|
|
24
64
|
env: process.env,
|
|
25
65
|
uid: () => (typeof process.getuid === 'function' ? process.getuid() : -1),
|
|
66
|
+
pid: () => process.pid,
|
|
67
|
+
hostname: () => hostname(),
|
|
68
|
+
processAlive(pid) {
|
|
69
|
+
try {
|
|
70
|
+
process.kill(pid, 0);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
// EPERM: it exists, under another user.
|
|
75
|
+
return error.code === 'EPERM';
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
async createExclusive(path, content, mode) {
|
|
79
|
+
try {
|
|
80
|
+
await writeFile(path, content, { mode, flag: 'wx' });
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error.code === 'EEXIST')
|
|
85
|
+
return false;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
onSignal(listener, options = {}) {
|
|
90
|
+
const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
91
|
+
let heard = 0;
|
|
92
|
+
const handler = (signal) => {
|
|
93
|
+
heard++;
|
|
94
|
+
if (heard === 1) {
|
|
95
|
+
listener(signal);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// Our own SIGTERM to the group below comes back here: already stopping.
|
|
99
|
+
if (heard > 2)
|
|
100
|
+
return;
|
|
101
|
+
if (options.second)
|
|
102
|
+
options.second(signal);
|
|
103
|
+
else
|
|
104
|
+
output.error(secondSignalMessage(signal));
|
|
105
|
+
stopOwnGroup();
|
|
106
|
+
process.exit(signal === 'SIGINT' ? 130 : signal === 'SIGHUP' ? 129 : 143);
|
|
107
|
+
};
|
|
108
|
+
for (const signal of SIGNALS)
|
|
109
|
+
process.on(signal, handler);
|
|
110
|
+
return () => { for (const signal of SIGNALS)
|
|
111
|
+
process.off(signal, handler); };
|
|
112
|
+
},
|
|
26
113
|
interactive: () => Boolean(process.stdin.isTTY) && !process.env['CI'],
|
|
27
114
|
now: () => new Date(),
|
|
28
115
|
randomHex: (bytes) => randomBytes(bytes).toString('hex'),
|
|
@@ -34,6 +121,8 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
34
121
|
for (const key of options.unset ?? [])
|
|
35
122
|
delete base[key];
|
|
36
123
|
const env = { ...base, ...options.env };
|
|
124
|
+
if (options.env?.['PATH'] === undefined)
|
|
125
|
+
env['PATH'] = withOwnNode(env['PATH'], process.execPath);
|
|
37
126
|
let fd;
|
|
38
127
|
if (options.stdoutFile) {
|
|
39
128
|
fd = openSync(options.stdoutFile, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, 0o600);
|
|
@@ -41,22 +130,54 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
41
130
|
return new Promise((resolve) => {
|
|
42
131
|
let stdout = '';
|
|
43
132
|
let stderr = '';
|
|
133
|
+
const sink = options.stream ? options.onOutput : undefined;
|
|
44
134
|
const child = spawn(command, args, {
|
|
45
135
|
cwd: options.cwd,
|
|
46
136
|
env,
|
|
47
|
-
stdio: options.
|
|
137
|
+
stdio: options.interactive ? 'inherit'
|
|
138
|
+
: sink ? ['ignore', 'pipe', 'pipe']
|
|
139
|
+
: options.stream ? ['ignore', 'inherit', 'inherit']
|
|
140
|
+
: [options.stdin === undefined ? 'ignore' : 'pipe', fd ?? 'pipe', 'pipe'],
|
|
48
141
|
});
|
|
49
142
|
if (options.stdin !== undefined)
|
|
50
143
|
child.stdin?.end(options.stdin);
|
|
51
|
-
|
|
52
|
-
|
|
144
|
+
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
|
|
145
|
+
if (sink) {
|
|
146
|
+
child.stdout?.on('data', (chunk) => sink(decoders.stdout.write(chunk), 'stdout'));
|
|
147
|
+
child.stderr?.on('data', (chunk) => sink(decoders.stderr.write(chunk), 'stderr'));
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
|
|
151
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
|
|
152
|
+
}
|
|
153
|
+
let finished = false;
|
|
53
154
|
const done = (code) => {
|
|
155
|
+
if (finished)
|
|
156
|
+
return;
|
|
157
|
+
finished = true;
|
|
54
158
|
if (fd !== undefined)
|
|
55
159
|
closeSync(fd);
|
|
160
|
+
if (sink) {
|
|
161
|
+
// A process the child left behind may still hold the pipes: stop reading them.
|
|
162
|
+
child.stdout?.destroy();
|
|
163
|
+
child.stderr?.destroy();
|
|
164
|
+
sink(decoders.stdout.end(), 'stdout');
|
|
165
|
+
sink(decoders.stderr.end(), 'stderr');
|
|
166
|
+
}
|
|
56
167
|
resolve({ code, stdout, stderr });
|
|
57
168
|
};
|
|
58
169
|
child.on('error', (error) => { stderr += error.message; done(127); });
|
|
59
170
|
child.on('close', (code) => done(code ?? 1));
|
|
171
|
+
if (sink) {
|
|
172
|
+
// Piped (--json), 'close' waits for every holder of the pipes — a
|
|
173
|
+
// background process a hook or a build started would hold the deploy
|
|
174
|
+
// (and its lock) forever, where the terminal's inherited stdio would
|
|
175
|
+
// not. The child's exit ends it; what it wrote just before still
|
|
176
|
+
// arrives within the grace period.
|
|
177
|
+
child.on('exit', (code) => {
|
|
178
|
+
setTimeout(() => done(code ?? 1), PIPE_GRACE_MS);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
60
181
|
});
|
|
61
182
|
},
|
|
62
183
|
async readFile(path) {
|
|
@@ -91,7 +212,7 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
91
212
|
try {
|
|
92
213
|
const s = await lstat(path);
|
|
93
214
|
const kind = s.isSymbolicLink() ? 'symlink' : s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other';
|
|
94
|
-
return { kind, size: s.size };
|
|
215
|
+
return { kind, size: s.size, mode: s.mode & 0o7777, uid: s.uid, gid: s.gid };
|
|
95
216
|
}
|
|
96
217
|
catch {
|
|
97
218
|
return undefined;
|
|
@@ -106,10 +227,60 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
106
227
|
}
|
|
107
228
|
},
|
|
108
229
|
symlink: (target, path) => symlink(target, path),
|
|
230
|
+
chmod: (path, mode) => chmod(path, mode),
|
|
231
|
+
async realpath(path) {
|
|
232
|
+
try {
|
|
233
|
+
return await realpath(path);
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
async readPlainFile(path, maxBytes) {
|
|
240
|
+
const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
241
|
+
try {
|
|
242
|
+
const s = await handle.stat();
|
|
243
|
+
if (!s.isFile())
|
|
244
|
+
throw new Error(`${path} is not a regular file`);
|
|
245
|
+
if (s.size > maxBytes)
|
|
246
|
+
throw new Error(`${path} is larger than ${maxBytes} bytes`);
|
|
247
|
+
return await handle.readFile('utf8');
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
await handle.close();
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
async secureOwner(path, { uid, gid, mode, kind }) {
|
|
254
|
+
const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK | (kind === 'dir' ? constants.O_DIRECTORY : 0));
|
|
255
|
+
try {
|
|
256
|
+
const s = await handle.stat();
|
|
257
|
+
if (kind === 'file' && !s.isFile())
|
|
258
|
+
throw new Error(`${path} is not a regular file`);
|
|
259
|
+
if (kind === 'dir' && !s.isDirectory())
|
|
260
|
+
throw new Error(`${path} is not a directory`);
|
|
261
|
+
// A hard link to another file (a password file, say) would change that file too.
|
|
262
|
+
if (kind === 'file' && s.nlink !== 1)
|
|
263
|
+
throw new Error(`${path} has ${s.nlink} hard links`);
|
|
264
|
+
await handle.chown(uid, gid);
|
|
265
|
+
await handle.chmod(mode);
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
await handle.close();
|
|
269
|
+
}
|
|
270
|
+
},
|
|
109
271
|
async mkdir(path, mode) {
|
|
110
272
|
await mkdir(path, { recursive: true, ...(mode === undefined ? {} : { mode }) });
|
|
111
273
|
},
|
|
112
274
|
remove: (path) => rm(path, { force: true, recursive: true }),
|
|
275
|
+
async removeFile(path) {
|
|
276
|
+
try {
|
|
277
|
+
await unlink(path);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
if (error.code !== 'ENOENT')
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
},
|
|
113
284
|
async list(dir) {
|
|
114
285
|
try {
|
|
115
286
|
return await readdir(dir);
|
|
@@ -124,15 +295,11 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
124
295
|
// The question and the echo go to stderr: anything a prompt writes to
|
|
125
296
|
// stdout can end up inside a captured value (RFC 0006 §A, incident 5).
|
|
126
297
|
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
127
|
-
if (secret) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
process.stderr.write(s);
|
|
133
|
-
asked = true;
|
|
134
|
-
}
|
|
135
|
-
};
|
|
298
|
+
if (secret && !muteEcho(rl, (s) => process.stderr.write(s))) {
|
|
299
|
+
// Fail closed: never ask for a secret that would be echoed.
|
|
300
|
+
rl.close();
|
|
301
|
+
output.warn('this Node cannot hide what is typed: give the secret in the environment of the command instead');
|
|
302
|
+
return undefined;
|
|
136
303
|
}
|
|
137
304
|
const answer = await new Promise((resolve) => rl.question(` ${question}: `, resolve));
|
|
138
305
|
rl.close();
|
|
@@ -148,36 +315,80 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
148
315
|
rl.close();
|
|
149
316
|
return /^y(es)?$/i.test(answer.trim());
|
|
150
317
|
},
|
|
151
|
-
tlsCertificate(servername) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
318
|
+
tlsCertificate: (servername) => probeTls(servername, { host: servername, port: 443 }),
|
|
319
|
+
async createLog(path, mode) {
|
|
320
|
+
const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_APPEND, mode);
|
|
321
|
+
return {
|
|
322
|
+
fd,
|
|
323
|
+
append(text) {
|
|
324
|
+
const bytes = Buffer.from(text, 'utf8');
|
|
325
|
+
for (let written = 0; written < bytes.length;)
|
|
326
|
+
written += writeSync(fd, bytes, written);
|
|
327
|
+
},
|
|
328
|
+
close() { closeSync(fd); },
|
|
329
|
+
};
|
|
330
|
+
},
|
|
331
|
+
async readFileRange(path, offset, length) {
|
|
332
|
+
const handle = await openNoFollow(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
333
|
+
try {
|
|
334
|
+
const s = await handle.stat();
|
|
335
|
+
if (!s.isFile())
|
|
336
|
+
throw new Error(`${path} is not a regular file`);
|
|
337
|
+
const data = Buffer.alloc(Math.max(0, Math.min(length, s.size - offset)));
|
|
338
|
+
let read = 0;
|
|
339
|
+
while (read < data.length) {
|
|
340
|
+
const { bytesRead } = await handle.read(data, read, data.length - read, offset + read);
|
|
341
|
+
if (bytesRead === 0)
|
|
342
|
+
break;
|
|
343
|
+
read += bytesRead;
|
|
344
|
+
}
|
|
345
|
+
return { data: data.subarray(0, read), size: s.size, uid: s.uid, mode: s.mode & 0o7777 };
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
await handle.close();
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
spawnDetached(command, args, options) {
|
|
352
|
+
return new Promise((resolve, reject) => {
|
|
353
|
+
if (options.stdout.fd === undefined) {
|
|
354
|
+
reject(new Error('the run log has no descriptor'));
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const child = spawn(command, args, {
|
|
358
|
+
cwd: options.cwd,
|
|
359
|
+
env: options.env,
|
|
360
|
+
// setsid(2): its own session and process group, no controlling terminal.
|
|
361
|
+
detached: true,
|
|
362
|
+
stdio: ['pipe', options.stdout.fd, 'ignore'],
|
|
173
363
|
});
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
364
|
+
child.once('error', reject);
|
|
365
|
+
child.once('spawn', () => {
|
|
366
|
+
child.stdin?.end(options.stdin);
|
|
367
|
+
child.unref();
|
|
368
|
+
resolve({ pid: child.pid });
|
|
178
369
|
});
|
|
179
370
|
});
|
|
180
371
|
},
|
|
372
|
+
kill(pid, signal) { process.kill(pid, signal); },
|
|
373
|
+
processGroupAlive(pgid) {
|
|
374
|
+
try {
|
|
375
|
+
process.kill(-pgid, 0);
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
return error.code === 'EPERM';
|
|
380
|
+
}
|
|
381
|
+
},
|
|
382
|
+
async processCmdline(pid) {
|
|
383
|
+
if (process.platform !== 'linux')
|
|
384
|
+
return undefined;
|
|
385
|
+
try {
|
|
386
|
+
return (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\u0000').filter(Boolean);
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
return undefined;
|
|
390
|
+
}
|
|
391
|
+
},
|
|
181
392
|
httpGet(url, options = {}) {
|
|
182
393
|
return new Promise((resolve) => {
|
|
183
394
|
const target = new URL(url);
|
|
@@ -197,5 +408,69 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
197
408
|
},
|
|
198
409
|
};
|
|
199
410
|
}
|
|
411
|
+
/**
|
|
412
|
+
* Readline echoes what is typed through its internal `_writeToOutput`; a
|
|
413
|
+
* secret answer replaces it so only the question is written. Returns false
|
|
414
|
+
* when that internal is gone (a Node that changed it): the caller must not
|
|
415
|
+
* ask then — fail closed, never echo a secret.
|
|
416
|
+
*/
|
|
417
|
+
export function muteEcho(rl, write) {
|
|
418
|
+
const writer = rl;
|
|
419
|
+
if (typeof writer._writeToOutput !== 'function')
|
|
420
|
+
return false;
|
|
421
|
+
let asked = false;
|
|
422
|
+
writer._writeToOutput = (text) => {
|
|
423
|
+
if (!asked) {
|
|
424
|
+
write(text);
|
|
425
|
+
asked = true;
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* The certificate `host:port` presents for `servername`. The chain is
|
|
432
|
+
* verified as any client would (the system's roots), but an untrusted or
|
|
433
|
+
* expired one is REPORTED, with its names and expiry, instead of failing the
|
|
434
|
+
* handshake — what C8 says to the operator. Only network failures are
|
|
435
|
+
* errors. Nothing is sent over the connection.
|
|
436
|
+
*/
|
|
437
|
+
export function probeTls(servername, target) {
|
|
438
|
+
return new Promise((resolve) => {
|
|
439
|
+
const socket = tls.connect({
|
|
440
|
+
host: target.host, port: target.port, servername, timeout: target.timeoutMs ?? 10_000,
|
|
441
|
+
// Reported, not refused: `authorized` says whether the chain verifies.
|
|
442
|
+
rejectUnauthorized: false,
|
|
443
|
+
// The name check is ours (covers()): a name mismatch is not a trust error.
|
|
444
|
+
checkServerIdentity: () => undefined,
|
|
445
|
+
});
|
|
446
|
+
const finish = (value) => { socket.destroy(); resolve(value); };
|
|
447
|
+
socket.once('secureConnect', () => {
|
|
448
|
+
const cert = socket.getPeerCertificate();
|
|
449
|
+
const names = (cert.subjectaltname ?? '')
|
|
450
|
+
.split(',')
|
|
451
|
+
.map((entry) => entry.trim())
|
|
452
|
+
.filter((entry) => entry.startsWith('DNS:'))
|
|
453
|
+
.map((entry) => entry.slice(4).toLowerCase());
|
|
454
|
+
const trustError = socket.authorized ? undefined : String(socket.authorizationError ?? 'unknown');
|
|
455
|
+
finish({ names, validTo: new Date(cert.valid_to), trusted: socket.authorized, ...(trustError ? { trustError } : {}) });
|
|
456
|
+
});
|
|
457
|
+
socket.once('timeout', () => finish({ error: 'timed out' }));
|
|
458
|
+
socket.once('error', (error) => finish({ error: error.message }));
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
/** open(2) with O_NOFOLLOW: a symlink at `path` is an error that says so. */
|
|
462
|
+
async function openNoFollow(path, flags) {
|
|
463
|
+
try {
|
|
464
|
+
return await open(path, flags | constants.O_NOFOLLOW);
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
const code = error.code;
|
|
468
|
+
if (code === 'ELOOP' || code === 'EMLINK')
|
|
469
|
+
throw new Error(`${path} is a symbolic link — refused, never followed`);
|
|
470
|
+
if (code === 'ENOTDIR')
|
|
471
|
+
throw new Error(`${path} is not a directory`);
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
200
475
|
/** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
|
|
201
476
|
export const parentOf = (path) => dirname(path);
|