@stagepass/cli 2.2.1 → 2.2.7

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.
@@ -1,9 +1,10 @@
1
- import { execa } from 'execa';
1
+ import { execa as defaultExeca } from 'execa';
2
2
  import chalk from 'chalk';
3
3
  import path from 'path';
4
4
  import fs from 'fs-extra';
5
+ import os from 'node:os';
5
6
  import inquirer from 'inquirer';
6
- import ora from 'ora';
7
+ import { createSpinner } from '../lib/spinner.js';
7
8
  import {
8
9
  getCaddyfilePath,
9
10
  getServerLogPath,
@@ -14,54 +15,219 @@ import {
14
15
  ensureCaddyfileMigrated,
15
16
  warnIfAllowAllOriginsActive,
16
17
  } from '../lib/migrate.js';
18
+ import { parseLsofListenOutput } from '../lib/doctor.js';
19
+ import {
20
+ getAutostartStatus,
21
+ buildLaunchctlBootstrapArgs,
22
+ buildLaunchctlKickstartArgs,
23
+ LAUNCH_AGENT_LABEL,
24
+ } from '../lib/autostart.js';
25
+
26
+ const PORT_IGNORE = [
27
+ 'Google Chrome',
28
+ 'Chrome Helper',
29
+ 'OneDrive',
30
+ 'Music',
31
+ 'Safari',
32
+ 'caddy',
33
+ ];
17
34
 
18
- // --- HELPERS ---
35
+ /**
36
+ * @param {unknown} pid
37
+ * @returns {boolean}
38
+ */
39
+ export function isSafePid(pid) {
40
+ return typeof pid === 'string'
41
+ ? /^[1-9][0-9]*$/.test(pid)
42
+ : typeof pid === 'number' && Number.isInteger(pid) && pid > 0;
43
+ }
19
44
 
20
- async function checkPort443() {
45
+ /**
46
+ * Inspect TCP 443 without sudo (same approach as doctor).
47
+ * @param {object} [opts]
48
+ * @param {typeof defaultExeca} [opts.execa]
49
+ * @returns {Promise<{ pid: string, name: string }|null>}
50
+ */
51
+ export async function findPort443Conflict(opts = {}) {
52
+ const run = opts.execa || defaultExeca;
21
53
  try {
22
- const cmd = "sudo lsof -iTCP:443 -n -P | grep LISTEN | awk '{print $2}'";
23
- const { stdout: rawOutput } = await execa(cmd, { shell: true });
24
-
25
- if (!rawOutput || !rawOutput.trim()) return null;
26
-
27
- const pids = rawOutput.trim().split('\n');
28
- const pid = pids[0].trim();
29
- if (!pid) return null;
30
-
31
- const { stdout: commandPath } = await execa('ps', ['-p', pid, '-o', 'comm=']);
32
- const name = path.basename(commandPath.trim());
33
-
34
- const ignoreList = ['Google Chrome', 'Chrome Helper', 'OneDrive', 'Music', 'Safari', 'caddy'];
35
- if (ignoreList.some(ignore => name.includes(ignore))) {
36
- return null;
54
+ const { stdout } = await run('lsof', [
55
+ '-nP',
56
+ '-iTCP:443',
57
+ '-sTCP:LISTEN',
58
+ ]);
59
+ const listeners = parseLsofListenOutput(stdout);
60
+ for (const listener of listeners) {
61
+ const name = listener.name || path.basename(listener.command || '');
62
+ if (PORT_IGNORE.some((ignore) => name.includes(ignore))) continue;
63
+ if (/^caddy$/i.test(name)) continue;
64
+ return { pid: String(listener.pid), name };
37
65
  }
66
+ return null;
67
+ } catch (error) {
68
+ const err = /** @type {{ exitCode?: number, code?: string|number }} */ (error);
69
+ // lsof exits 1 when nothing matches
70
+ if (err.exitCode === 1 || err.code === 1 || err.code === '1') return null;
71
+ return null;
72
+ }
73
+ }
38
74
 
39
- return { pid, name };
40
- } catch (e) {
41
- return null;
75
+ /**
76
+ * @param {object} opts
77
+ * @param {string} opts.message
78
+ * @param {boolean} [opts.default]
79
+ * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [opts.confirm]
80
+ * @param {boolean} [opts.interactive]
81
+ */
82
+ async function askConfirm(opts) {
83
+ if (typeof opts.confirm === 'function') {
84
+ return opts.confirm(opts.message, { default: opts.default === true });
85
+ }
86
+ if (opts.interactive === false || !process.stdin.isTTY) {
87
+ return false;
42
88
  }
89
+ const { value } = await inquirer.prompt([
90
+ {
91
+ type: 'confirm',
92
+ name: 'value',
93
+ message: opts.message,
94
+ default: opts.default === true,
95
+ },
96
+ ]);
97
+ return Boolean(value);
43
98
  }
44
99
 
45
- async function killProcess(proc) {
100
+ /**
101
+ * Send a signal; use sudo only if the unprivileged kill fails.
102
+ * @param {string} pid
103
+ * @param {'TERM'|'KILL'} signal
104
+ * @param {typeof defaultExeca} run
105
+ */
106
+ async function signalProcess(pid, signal, run) {
107
+ const flag = signal === 'KILL' ? '-KILL' : '-TERM';
46
108
  try {
47
- if (proc.name.includes('nginx')) {
48
- try { await execa('valet', ['stop']); return true; } catch (e) {}
49
- try { await execa('brew', ['services', 'stop', 'nginx']); return true; } catch (e) {}
109
+ await run('kill', [flag, pid]);
110
+ return { ok: true, usedSudo: false };
111
+ } catch {
112
+ await run('sudo', ['kill', flag, pid], { stdio: 'inherit' });
113
+ return { ok: true, usedSudo: true };
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Resolve a confirmed port conflict: TERM first, KILL only after a second confirm
119
+ * if the listener is still present. Never signals without confirmation.
120
+ *
121
+ * @param {{ pid: string, name: string }} proc
122
+ * @param {object} opts
123
+ * @param {typeof defaultExeca} [opts.execa]
124
+ * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [opts.confirm]
125
+ * @param {boolean} [opts.interactive]
126
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
127
+ * @param {() => Promise<{ pid: string, name: string }|null>} [opts.recheck]
128
+ * @returns {Promise<{ ok: boolean, cancelled?: boolean, detail?: string }>}
129
+ */
130
+ export async function resolvePort443Conflict(proc, opts = {}) {
131
+ const run = opts.execa || defaultExeca;
132
+ const sleep =
133
+ opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
134
+ const recheck = opts.recheck || (() => findPort443Conflict({ execa: run }));
135
+ const pid = String(proc?.pid ?? '');
136
+
137
+ if (!isSafePid(pid)) {
138
+ return {
139
+ ok: false,
140
+ detail: `Refusing to signal process: invalid PID "${proc?.pid}".`,
141
+ };
142
+ }
143
+
144
+ console.log(
145
+ chalk.yellow(
146
+ `\nāš ļø Port 443 is blocked by: ${chalk.bold(proc.name)} (PID ${pid})`
147
+ )
148
+ );
149
+
150
+ const shouldTerm = await askConfirm({
151
+ message: `Send SIGTERM to ${proc.name} (PID ${pid}) to free port 443?`,
152
+ default: false,
153
+ confirm: opts.confirm,
154
+ interactive: opts.interactive,
155
+ });
156
+ if (!shouldTerm) {
157
+ return { ok: false, cancelled: true };
158
+ }
159
+
160
+ // Prefer service stop helpers when the name is a known reverse proxy / httpd.
161
+ if (String(proc.name).includes('nginx')) {
162
+ try {
163
+ await run('valet', ['stop']);
164
+ } catch {
165
+ try {
166
+ await run('brew', ['services', 'stop', 'nginx']);
167
+ } catch {
168
+ await signalProcess(pid, 'TERM', run);
169
+ }
50
170
  }
51
- if (proc.name.includes('httpd')) {
52
- await execa('sudo', ['apachectl', 'stop']);
53
- return true;
171
+ } else if (String(proc.name).includes('httpd')) {
172
+ try {
173
+ await run('sudo', ['apachectl', 'stop'], { stdio: 'inherit' });
174
+ } catch {
175
+ await signalProcess(pid, 'TERM', run);
54
176
  }
55
- await execa('sudo', ['kill', '-9', proc.pid]);
56
- return true;
57
- } catch (error) {
58
- return false;
177
+ } else {
178
+ await signalProcess(pid, 'TERM', run);
59
179
  }
60
- }
61
180
 
62
- // --- MAIN COMMAND ---
181
+ await sleep(400);
182
+ let still = await recheck();
183
+ if (!still || String(still.pid) !== pid) {
184
+ return { ok: true, detail: 'SIGTERM' };
185
+ }
63
186
 
187
+ const shouldKill = await askConfirm({
188
+ message: `${proc.name} (PID ${pid}) is still listening. Send SIGKILL?`,
189
+ default: false,
190
+ confirm: opts.confirm,
191
+ interactive: opts.interactive,
192
+ });
193
+ if (!shouldKill) {
194
+ return {
195
+ ok: false,
196
+ cancelled: true,
197
+ detail: 'Still listening after SIGTERM; SIGKILL not confirmed.',
198
+ };
199
+ }
200
+
201
+ await signalProcess(pid, 'KILL', run);
202
+ await sleep(200);
203
+ still = await recheck();
204
+ if (still && String(still.pid) === pid) {
205
+ return {
206
+ ok: false,
207
+ detail: `PID ${pid} still listening after SIGKILL.`,
208
+ };
209
+ }
210
+ return { ok: true, detail: 'SIGKILL' };
211
+ }
212
+
213
+ /**
214
+ * @param {object} [options]
215
+ * @param {boolean} [options.verbose]
216
+ * @param {typeof defaultExeca} [options.execa]
217
+ * @param {(message: string, o?: { default?: boolean }) => Promise<boolean>} [options.confirm]
218
+ * @param {boolean} [options.interactive]
219
+ * @param {typeof getAutostartStatus} [options.getAutostartStatus]
220
+ * @param {typeof findPort443Conflict} [options.findPort443Conflict]
221
+ * @param {typeof resolvePort443Conflict} [options.resolvePort443Conflict]
222
+ * @param {number} [options.uid]
223
+ * @param {(ms: number) => Promise<void>} [options.sleep]
224
+ */
64
225
  export async function start(options = {}) {
226
+ const run = options.execa || defaultExeca;
227
+ const interactive =
228
+ options.interactive !== undefined
229
+ ? options.interactive
230
+ : Boolean(process.stdin.isTTY);
65
231
  const caddyDir = getStagepassDir();
66
232
  const caddyFile = getCaddyfilePath();
67
233
  const logFile = getServerLogPath();
@@ -69,82 +235,150 @@ export async function start(options = {}) {
69
235
 
70
236
  console.log(chalk.bold('\nšŸš€ Starting Stagepass...'));
71
237
 
72
- // 1. Sudo warm-up (interactive, before spinner starts)
73
- try {
74
- await execa('sudo', ['-v'], { stdio: 'inherit' });
75
- } catch (e) {
76
- console.log(chalk.red('āŒ Root permissions required.'));
77
- return;
78
- }
79
-
80
- // 2. Port check (interactive)
81
- const conflict = await checkPort443();
238
+ // 1. Port conflict — no sudo until the user confirms a signal that needs it.
239
+ const conflict =
240
+ (await (options.findPort443Conflict || findPort443Conflict)({
241
+ execa: run,
242
+ })) || null;
82
243
  if (conflict) {
83
- console.log(chalk.yellow(`\nāš ļø Port 443 is blocked by: ${chalk.bold(conflict.name)}`));
84
- const { shouldKill } = await inquirer.prompt([{
85
- type: 'confirm',
86
- name: 'shouldKill',
87
- message: 'Auto-fix conflict?',
88
- default: true
89
- }]);
90
-
91
- if (shouldKill) {
92
- const killSpinner = ora('Freeing port...').start();
93
- const success = await killProcess(conflict);
94
- if (success) killSpinner.succeed('Port freed.');
95
- else {
96
- killSpinner.fail('Could not free port.');
97
- return;
98
- }
99
- } else {
244
+ if (!interactive && typeof options.confirm !== 'function') {
245
+ console.log(
246
+ chalk.red(
247
+ `Port 443 is blocked by ${conflict.name} (PID ${conflict.pid}). Refusing to signal without confirmation.`
248
+ )
249
+ );
250
+ return;
251
+ }
252
+ const resolved = await (options.resolvePort443Conflict ||
253
+ resolvePort443Conflict)(conflict, {
254
+ execa: run,
255
+ confirm: options.confirm,
256
+ interactive,
257
+ sleep: options.sleep,
258
+ });
259
+ if (!resolved.ok) {
260
+ if (resolved.detail) console.log(chalk.red(resolved.detail));
100
261
  return;
101
262
  }
263
+ console.log(chalk.green(`Port freed (${resolved.detail}).`));
102
264
  }
103
265
 
104
- // 2b. Migrate legacy Caddyfile blocks before boot
266
+ // 2. Migrate legacy Caddyfile blocks before boot
105
267
  await fs.ensureDir(caddyDir);
106
268
  if (await fs.pathExists(caddyFile)) {
107
269
  await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
108
270
  await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFile });
109
271
  }
110
272
 
111
- // 3. Boot services
112
- const spinner = ora('Booting background services...').start();
113
-
114
- // Prepare logging (standard mode)
273
+ // 3. Boot services (autostart-aware kickstart when LaunchAgent is installed)
274
+ const spinner = createSpinner('Booting background services...').start();
275
+
276
+ /** @type {number|null} */
277
+ let logFd = null;
115
278
  let stdioMode = 'ignore';
116
279
  if (options.verbose) {
117
280
  spinner.stop();
118
281
  console.log(chalk.dim('--- Verbose Logs ---'));
119
282
  stdioMode = 'inherit';
120
283
  } else {
121
- // Redirect stdout/stderr to logfile
122
- const logStream = fs.openSync(logFile, 'w');
123
- stdioMode = ['ignore', logStream, logStream];
284
+ logFd = fs.openSync(logFile, 'w');
285
+ stdioMode = ['ignore', logFd, logFd];
124
286
  }
125
287
 
126
288
  try {
127
- // Start PHP
289
+ // PHP: preserve public brew services restart (no root warm-up).
290
+ try {
291
+ await run('brew', ['services', 'restart', 'php'], {
292
+ stdio: stdioMode === 'inherit' ? 'inherit' : 'ignore',
293
+ });
294
+ } catch {
295
+ /* ignore php errors */
296
+ }
297
+
298
+ /** @type {{ loaded?: boolean, plistExists?: boolean, plistPath?: string }} */
299
+ let status = {};
128
300
  try {
129
- await execa('brew', ['services', 'restart', 'php'], { stdio: stdioMode === 'inherit' ? 'inherit' : 'ignore' });
130
- } catch (e) { /* ignore php errors */ }
301
+ status =
302
+ (await (options.getAutostartStatus || getAutostartStatus)({})) || {};
303
+ } catch {
304
+ status = {};
305
+ }
306
+ const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
307
+
308
+ if (status.loaded || status.plistExists) {
309
+ if (status.plistExists && !status.loaded && status.plistPath) {
310
+ try {
311
+ await run(
312
+ 'launchctl',
313
+ buildLaunchctlBootstrapArgs(uid, status.plistPath)
314
+ );
315
+ console.log(
316
+ chalk.dim(
317
+ `Bootstrapped LaunchAgent ${LAUNCH_AGENT_LABEL} (was installed but not loaded).`
318
+ )
319
+ );
320
+ } catch (error) {
321
+ if (!options.verbose) spinner.fail('Failed to bootstrap LaunchAgent.');
322
+ console.log(
323
+ chalk.red(error instanceof Error ? error.message : String(error))
324
+ );
325
+ return;
326
+ }
327
+ }
328
+ try {
329
+ await run('launchctl', buildLaunchctlKickstartArgs(uid));
330
+ if (!options.verbose) {
331
+ spinner.succeed(
332
+ chalk.green(
333
+ `Stagepass is active (launchctl kickstart ${LAUNCH_AGENT_LABEL}).`
334
+ )
335
+ );
336
+ console.log(chalk.dim(` Logs: ${logFile}`));
337
+ } else {
338
+ console.log(
339
+ chalk.green(`āœ” kickstart gui/${uid}/${LAUNCH_AGENT_LABEL}`)
340
+ );
341
+ }
342
+ return;
343
+ } catch (error) {
344
+ if (!options.verbose) spinner.fail('launchctl kickstart failed.');
345
+ console.log(
346
+ chalk.red(error instanceof Error ? error.message : String(error))
347
+ );
348
+ console.log(chalk.dim('Falling back to direct caddy start...'));
349
+ if (!options.verbose) spinner.start('Booting background services...');
350
+ }
351
+ }
131
352
 
132
- // Start Caddy
133
- // Stop old first
134
- try { await execa('caddy', ['stop']); } catch (e) {}
353
+ try {
354
+ await run('caddy', ['stop']);
355
+ } catch {
356
+ /* ignore */
357
+ }
135
358
 
136
- await execa('caddy', ['start', '--config', caddyFile], { stdio: stdioMode });
359
+ await run('caddy', ['start', '--config', caddyFile], { stdio: stdioMode });
137
360
 
138
361
  if (!options.verbose) {
139
- spinner.succeed(chalk.green('Stagepass is active.'));
140
- console.log(chalk.dim(` Logs: ${logFile}`));
362
+ spinner.succeed(chalk.green('Stagepass is active.'));
363
+ console.log(chalk.dim(` Logs: ${logFile}`));
364
+ } else {
365
+ console.log(chalk.green('āœ” Stagepass is active.'));
141
366
  }
142
-
143
367
  } catch (error) {
144
368
  spinner.fail('Failed to start.');
145
369
  if (!options.verbose) {
146
- console.log(chalk.red('See error log for details:'));
147
- console.log(chalk.dim(logFile));
370
+ console.log(chalk.red('See error log for details:'));
371
+ console.log(chalk.dim(logFile));
372
+ } else if (error instanceof Error) {
373
+ console.log(chalk.red(error.message));
374
+ }
375
+ } finally {
376
+ if (logFd != null) {
377
+ try {
378
+ fs.closeSync(logFd);
379
+ } catch {
380
+ /* ignore */
381
+ }
148
382
  }
149
383
  }
150
- }
384
+ }
@@ -1,56 +1,84 @@
1
- import { execa } from 'execa';
1
+ import { execa as defaultExeca } from 'execa';
2
2
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { getAutostartStatus } from '../lib/autostart.js';
3
+ import os from 'node:os';
4
+ import { createSpinner } from '../lib/spinner.js';
5
+ import {
6
+ getAutostartStatus,
7
+ buildLaunchctlBootoutArgs,
8
+ LAUNCH_AGENT_LABEL,
9
+ } from '../lib/autostart.js';
5
10
 
11
+ /**
12
+ * @param {object} [options]
13
+ * @param {boolean} [options.verbose]
14
+ * @param {typeof defaultExeca} [options.execa]
15
+ * @param {typeof getAutostartStatus} [options.getAutostartStatus]
16
+ * @param {number} [options.uid]
17
+ */
6
18
  export async function stop(options = {}) {
19
+ const run = options.execa || defaultExeca;
7
20
  console.log(chalk.bold('\nšŸ›‘ Stopping Stagepass...'));
8
-
9
- const spinner = ora('Shutting down services...').start();
21
+
22
+ const spinner = createSpinner('Shutting down services...').start();
10
23
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
11
24
 
12
25
  if (options.verbose) {
13
- spinner.stop();
14
- console.log(chalk.dim('--- Verbose Logs ---'));
26
+ spinner.stop();
27
+ console.log(chalk.dim('--- Verbose Logs ---'));
15
28
  }
16
29
 
17
30
  try {
18
- // 1. Stop Caddy
31
+ /** @type {{ loaded?: boolean, plistExists?: boolean }} */
32
+ let status = { loaded: false, plistExists: false };
33
+ try {
34
+ status =
35
+ (await (options.getAutostartStatus || getAutostartStatus)({})) ||
36
+ status;
37
+ } catch {
38
+ // ignore status failures; still stop caddy/php
39
+ }
40
+ const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
41
+ let usedBootout = false;
42
+
43
+ // Bootout first so KeepAlive/RunAtLoad cannot immediately restart during stop.
44
+ if (status.loaded || status.plistExists) {
45
+ try {
46
+ await run('launchctl', buildLaunchctlBootoutArgs(uid));
47
+ usedBootout = true;
48
+ } catch {
49
+ // not loaded
50
+ }
51
+ }
52
+
19
53
  try {
20
- await execa('caddy', ['stop'], { stdio: stdioMode });
21
- } catch (e) {
54
+ await run('caddy', ['stop'], { stdio: stdioMode });
55
+ } catch {
22
56
  // Ignore if already stopped
23
57
  }
24
58
 
25
- // 2. Stop PHP (optional, but cleaner)
26
59
  try {
27
- await execa('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
28
- } catch (e) {
29
- // Ignore
60
+ await run('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
61
+ } catch {
62
+ // Ignore
30
63
  }
31
64
 
32
65
  if (!options.verbose) {
33
- spinner.succeed(chalk.green('Services stopped.'));
66
+ spinner.succeed(chalk.green('Services stopped.'));
34
67
  } else {
35
- console.log(chalk.green('āœ” Services stopped.'));
68
+ console.log(chalk.green('āœ” Services stopped.'));
36
69
  }
37
70
 
38
- // Non-breaking hint only: existing stop semantics stay unchanged.
39
- try {
40
- const status = await getAutostartStatus();
41
- if (status.loaded || status.plistExists) {
42
- console.log(
43
- chalk.dim(
44
- 'Autostart is enabled; Caddy may start again at next login. Use `stagepass autostart off` to disable permanently.'
45
- )
46
- );
47
- }
48
- } catch {
49
- // ignore status failures
71
+ if (usedBootout || status.loaded || status.plistExists) {
72
+ console.log(
73
+ chalk.dim(
74
+ `Autostart LaunchAgent ${LAUNCH_AGENT_LABEL} was stopped with launchctl bootout (until next login). Use \`stagepass autostart off\` to disable permanently.`
75
+ )
76
+ );
50
77
  }
51
-
52
78
  } catch (error) {
53
79
  if (!options.verbose) spinner.fail('Error stopping services.');
54
- console.error(chalk.red(error.message));
80
+ console.error(
81
+ chalk.red(error instanceof Error ? error.message : String(error))
82
+ );
55
83
  }
56
- }
84
+ }
@@ -2,7 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import { execa } from 'execa';
5
- import ora from 'ora';
5
+ import { createSpinner } from '../lib/spinner.js';
6
6
  import { resolveLinkDomain } from '../lib/domain.js';
7
7
  import { removeBlock } from '../lib/caddyfile.js';
8
8
  import { getCaddyfilePath, getProjectsPath } from '../lib/paths.js';
@@ -22,7 +22,7 @@ export async function unlink(domain, options = {}) {
22
22
  const caddyFilePath = getCaddyfilePath();
23
23
  const projectsPath = getProjectsPath();
24
24
 
25
- const spinner = ora(`Unlinking ${chalk.bold(targetDomain)}...`).start();
25
+ const spinner = createSpinner(`Unlinking ${chalk.bold(targetDomain)}...`).start();
26
26
 
27
27
  try {
28
28
  if (!(await fs.pathExists(caddyFilePath))) {