@stagepass/cli 2.2.6 → 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.
- package/README.md +33 -4
- package/TESTING-macos.md +13 -4
- package/package.json +1 -1
- package/src/commands/link.js +2 -2
- package/src/commands/reload.js +2 -2
- package/src/commands/setup.js +5 -5
- package/src/commands/start.js +317 -83
- package/src/commands/stop.js +59 -31
- package/src/commands/unlink.js +2 -2
- package/src/lib/autostart.js +300 -3
- package/src/lib/spinner.js +60 -0
- package/src/lib/versions.js +1 -1
package/README.md
CHANGED
|
@@ -49,11 +49,11 @@ Linked: https://my-project.sp -> /absolute/path/to/project
|
|
|
49
49
|
| Command | Description |
|
|
50
50
|
| :--- | :--- |
|
|
51
51
|
| `stagepass setup` | Install Caddy, PHP, Dnsmasq via Homebrew and configure the local `.sp` resolver (`address=/.sp/127.0.0.1` + `/etc/resolver/sp`). |
|
|
52
|
-
| `stagepass start` | Start
|
|
52
|
+
| `stagepass start` | Start Caddy & PHP. No unconditional root warm-up: inspects port 443 without sudo; signals only after confirm (TERM then optional KILL). With autostart installed, bootstraps/kickstarts the LaunchAgent (else direct `caddy start`). |
|
|
53
53
|
| `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. |
|
|
54
54
|
| `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
|
|
55
55
|
| `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed. |
|
|
56
|
-
| `stagepass stop` | Stop
|
|
56
|
+
| `stagepass stop` | Stop Caddy & PHP. If autostart is installed/loaded, `launchctl bootout` first (until next login); use `autostart off` to disable permanently. |
|
|
57
57
|
| `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, plus the current project's declared modules vs. its live site). Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
|
|
58
58
|
| `stagepass certs check` | Read-only Caddy local CA check (validity, System keychain trust, orphans, optional TLS handshake per linked domain). `--json`, `--skip-handshake`. |
|
|
59
59
|
| `stagepass certs trust` | Run `caddy trust` after interactive confirmation (or `--yes`). |
|
|
@@ -70,10 +70,28 @@ All commands support `-v, --verbose` where applicable.
|
|
|
70
70
|
|
|
71
71
|
- `doctor` and `certs check` are read-only. They never delete keychain items or certificate files.
|
|
72
72
|
- Prefer CDN major pin `@2` in Webflow custom code (doctor warns if recommended snippets would use `@latest`).
|
|
73
|
-
-
|
|
74
|
-
-
|
|
73
|
+
- Autostart runs as your user (same privilege model as interactive `caddy start`). `start` kickstarts the agent when present; `stop` bootouts until the next login. If port 443 cannot be bound, `daemon` logs a clear error and exits `0` so launchd KeepAlive does not restart-loop. Interactive `start` confirms before signalling any non-caddy listener.
|
|
74
|
+
- `stagepass autostart on` records a launchd-safe `PATH` from `brew --prefix` (Apple Silicon `/opt/homebrew`, Intel `/usr/local`) plus `/usr/bin:/bin:/usr/sbin:/sbin`. It does **not** copy your interactive shell environment. `brew` and `caddy` must resolve to shims under that prefix's `bin`/`sbin` (normal Homebrew Cellar symlinks are fine). Missing Homebrew/Caddy aborts **before** writing the plist.
|
|
75
75
|
- Manual macOS checklist: [`TESTING-macos.md`](./TESTING-macos.md).
|
|
76
76
|
|
|
77
|
+
#### macOS permissions (keep these separate)
|
|
78
|
+
|
|
79
|
+
These are different prompts. Grant only the narrow dialog macOS shows — Stagepass never asks for Full Disk Access or any security bypass.
|
|
80
|
+
|
|
81
|
+
| Concern | What it is | Typical fix |
|
|
82
|
+
| :--- | :--- | :--- |
|
|
83
|
+
| **System CA trust** | Trusting Caddy’s local CA in the System keychain (`stagepass certs trust` / `caddy trust`) so browsers accept `https://*.sp`. | Run `stagepass certs check`, then `certs trust` if needed. Unrelated to TCC file access. |
|
|
84
|
+
| **Browser Local Network Access** | Chrome (and similar) gating public HTTPS pages that fetch `https://*.sp` / loopback. | Allow Local Network for the **browser** when it prompts. Not a Node Desktop-files grant. |
|
|
85
|
+
| **Node files access (TCC)** | macOS may ask the **Node** binary for access to a folder (commonly **Desktop**) when the CLI or LaunchAgent reads a project / test package living there. | Grant that folder to Node if you intentionally keep projects on Desktop. Prefer installing the CLI in a stable location (below) so everyday use does not depend on Desktop TCC. |
|
|
86
|
+
|
|
87
|
+
#### Install location and LaunchAgent paths
|
|
88
|
+
|
|
89
|
+
- Prefer a **stable** global install (`npm install -g @stagepass/cli` into the normal npm prefix, or another fixed absolute path). Avoid pointing autostart at a temporary Desktop unpack / ad-hoc test tarball when you can use the published package instead.
|
|
90
|
+
- `autostart on` records **absolute** Node and CLI paths (often Homebrew Cellar Node + the realpathed `stagepass` entry) plus the validated Homebrew `PATH`. It does not follow later `brew` upgrades automatically.
|
|
91
|
+
- After a Homebrew Node upgrade/cleanup, moving the CLI, or changing the npm prefix, run `stagepass autostart on` again so ProgramArguments stay valid. A brief local outage while the agent reloads is expected.
|
|
92
|
+
- Upgrading the global CLI package does **not** rewrite an existing LaunchAgent that still points at an older test path. Switch deliberately: `stagepass autostart off` then `autostart on` with the stable CLI you want. Do **not** delete a test directory while a loaded agent still references it — disable/refresh the agent first.
|
|
93
|
+
- Development checkouts (`packages/cli`, Desktop test packs) and the published global install are different binaries; compare behaviour with one style at a time.
|
|
94
|
+
|
|
77
95
|
### `new` options
|
|
78
96
|
|
|
79
97
|
Scaffold a project with flags for every choice (interactive prompts only on a TTY without `--yes`):
|
|
@@ -239,6 +257,17 @@ stagepass link --no-allow-all-origins
|
|
|
239
257
|
|
|
240
258
|
Hand-written content outside `# START:` / `# END:` markers is left untouched. Unparsable legacy blocks are left unchanged with a warning. Migration is idempotent (second run does nothing and creates no new backup).
|
|
241
259
|
|
|
260
|
+
## Troubleshooting (CLI)
|
|
261
|
+
|
|
262
|
+
| Symptom | What to check |
|
|
263
|
+
| :--- | :--- |
|
|
264
|
+
| Autostart runs at login but `caddy: command not found` / daemon exits | Re-run `stagepass autostart on` on **2.2.7+** so the plist embeds Homebrew `PATH`. Confirm `brew --prefix` and that `which caddy` points at `$prefix/bin/caddy` (Cellar symlink OK). |
|
|
265
|
+
| macOS asks Node for Desktop access | Normal TCC when the CLI/agent reads a project under Desktop. Grant the folder or move the project / use a stable global CLI install. Not the same as browser Local Network or CA trust. |
|
|
266
|
+
| Autostart still runs an old Desktop test binary after `npm i -g` | Global upgrade does not migrate LaunchAgent ProgramArguments. `autostart off` then `on` with the stable CLI; do not remove the old path while the agent still references it. |
|
|
267
|
+
| `stagepass start` spinner floods the terminal (weird ANSI) | Upgrade to 2.2.7+ (spinner geometry guard). Rare with TTY width `0`. |
|
|
268
|
+
| `start` asks for a password at every boot | 2.2.7+ drops unconditional `sudo -v`. Only confirmed conflict resolution may use `sudo kill` / `apachectl`. |
|
|
269
|
+
| Port 443 bind failure under LaunchAgent | Expected when something else owns 443; daemon exits `0` (no restart loop). Free the port or use interactive `stagepass start`. |
|
|
270
|
+
|
|
242
271
|
## Related Packages
|
|
243
272
|
|
|
244
273
|
- `@stagepass/loader`: browser runtime for swapping production assets.
|
package/TESTING-macos.md
CHANGED
|
@@ -40,17 +40,26 @@ stagepass start
|
|
|
40
40
|
- [ ] After trust, Safari / Chrome / Firefox show a valid certificate for `https://my-project.sp`
|
|
41
41
|
- [ ] There is **no** `certs renew` command in 2.1.0
|
|
42
42
|
|
|
43
|
+
## Permissions (do not conflate)
|
|
44
|
+
|
|
45
|
+
- [ ] **CA trust** checked via `certs check` / `certs trust` (System keychain) — separate from TCC
|
|
46
|
+
- [ ] **Browser Local Network Access** granted in the browser if the live site loads `*.sp` — separate from Node
|
|
47
|
+
- [ ] If macOS prompts **Node** for **Desktop** (or another folder) access because the project/test pack lives there, grant that folder only — not Full Disk Access
|
|
48
|
+
- [ ] Prefer a stable `npm install -g @stagepass/cli` path for acceptance; temporary Desktop test packs are fine for a one-off check but refresh autostart before deleting them
|
|
49
|
+
|
|
43
50
|
## autostart / daemon
|
|
44
51
|
|
|
45
52
|
- [ ] `stagepass autostart status` shows label `io.github.arobertherz.stagepass`
|
|
46
|
-
- [ ] `stagepass autostart on` writes `~/Library/LaunchAgents/io.github.arobertherz.stagepass.plist` with absolute node + CLI paths
|
|
53
|
+
- [ ] `stagepass autostart on` writes `~/Library/LaunchAgents/io.github.arobertherz.stagepass.plist` with absolute node + CLI paths and an `EnvironmentVariables` `PATH` that includes Homebrew `bin`/`sbin` from `brew --prefix` (Cellar symlink for `caddy` is OK)
|
|
54
|
+
- [ ] With a sparse launchd-like PATH, `daemon` still finds `caddy` via the plist PATH
|
|
47
55
|
- [ ] Plist has `RunAtLoad` and `KeepAlive` / `SuccessfulExit` false
|
|
48
56
|
- [ ] Logs appear under `~/.stagepass/logs/`
|
|
49
|
-
- [ ]
|
|
50
|
-
- [ ]
|
|
57
|
+
- [ ] `stagepass start` does **not** prompt for sudo when port 443 is free / only caddy listens; with a foreign listener it asks before SIGTERM and again before SIGKILL
|
|
58
|
+
- [ ] With autostart on: bootstrap if needed, kickstart via `start`; `stop` bootouts (until next login) then stops Caddy/PHP; `autostart off` / `on` retained
|
|
59
|
+
- [ ] After moving Node/CLI or leaving a Desktop test path, `autostart off` then `on` with the stable CLI (upgrade alone does not migrate ProgramArguments)
|
|
51
60
|
- [ ] `stagepass autostart off` boots out the agent and removes the plist
|
|
52
61
|
- [ ] If port 443 cannot be bound, daemon logs a clear message and exits `0` (no KeepAlive restart-loop; not a silent success)
|
|
53
|
-
- [ ]
|
|
62
|
+
- [ ] Optional separate checklist: logout/login cold boot of **this** installed version (not assumed by the 2.2.7 interactive accept)
|
|
54
63
|
|
|
55
64
|
## Regression (must stay unchanged)
|
|
56
65
|
|
package/package.json
CHANGED
package/src/commands/link.js
CHANGED
|
@@ -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
|
|
5
|
+
import { createSpinner } from '../lib/spinner.js';
|
|
6
6
|
import { resolveLinkDomain } from '../lib/domain.js';
|
|
7
7
|
import { renderSiteBlock, upsertBlock, parseBlocks } from '../lib/caddyfile.js';
|
|
8
8
|
import {
|
|
@@ -87,7 +87,7 @@ export async function link(domain, options = {}) {
|
|
|
87
87
|
);
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
const spinner =
|
|
90
|
+
const spinner = createSpinner(`Linking ${chalk.bold(targetDomain)}...`).start();
|
|
91
91
|
|
|
92
92
|
try {
|
|
93
93
|
await fs.ensureDir(caddyDir);
|
package/src/commands/reload.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { execa } from 'execa';
|
|
3
|
-
import
|
|
3
|
+
import { createSpinner } from '../lib/spinner.js';
|
|
4
4
|
import fs from 'fs-extra';
|
|
5
5
|
import { getCaddyfilePath, getProjectsPath } from '../lib/paths.js';
|
|
6
6
|
import {
|
|
@@ -12,7 +12,7 @@ export async function reload(options = {}) {
|
|
|
12
12
|
const caddyFilePath = getCaddyfilePath();
|
|
13
13
|
const projectsPath = getProjectsPath();
|
|
14
14
|
|
|
15
|
-
const spinner =
|
|
15
|
+
const spinner = createSpinner('Reloading Caddy...').start();
|
|
16
16
|
|
|
17
17
|
if (!(await fs.pathExists(caddyFilePath))) {
|
|
18
18
|
spinner.fail('No Caddyfile found. Run "stagepass link" first.');
|
package/src/commands/setup.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execa } from 'execa';
|
|
2
|
-
import
|
|
2
|
+
import { createSpinner } from '../lib/spinner.js';
|
|
3
3
|
import chalk from 'chalk';
|
|
4
4
|
import fs from 'fs-extra';
|
|
5
5
|
import path from 'path';
|
|
@@ -21,7 +21,7 @@ export async function setup(options = {}) {
|
|
|
21
21
|
const execOpts = options.verbose ? { stdio: 'inherit' } : {};
|
|
22
22
|
|
|
23
23
|
// 1. Check Homebrew
|
|
24
|
-
const brewSpinner =
|
|
24
|
+
const brewSpinner = createSpinner('Checking system requirements...').start();
|
|
25
25
|
try {
|
|
26
26
|
await execa('brew', ['--version']);
|
|
27
27
|
brewSpinner.succeed('System requirements met.');
|
|
@@ -31,7 +31,7 @@ export async function setup(options = {}) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
// 2. Install Dependencies
|
|
34
|
-
const installSpinner =
|
|
34
|
+
const installSpinner = createSpinner('Installing dependencies...').start();
|
|
35
35
|
try {
|
|
36
36
|
await execa('brew', ['install', 'caddy', 'php', 'dnsmasq'], execOpts);
|
|
37
37
|
installSpinner.succeed('Core dependencies installed.');
|
|
@@ -41,7 +41,7 @@ export async function setup(options = {}) {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
// 3. Configure Dnsmasq (DIRECT WRITE STRATEGY)
|
|
44
|
-
const dnsSpinner =
|
|
44
|
+
const dnsSpinner = createSpinner('Configuring local DNS (.sp)...').start();
|
|
45
45
|
try {
|
|
46
46
|
const { stdout: brewPrefixRaw } = await execa('brew', ['--prefix']);
|
|
47
47
|
const brewPrefix = brewPrefixRaw.trim();
|
|
@@ -82,7 +82,7 @@ export async function setup(options = {}) {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
// 5. Restart DNS Services
|
|
85
|
-
const restartSpinner =
|
|
85
|
+
const restartSpinner = createSpinner('Restarting DNS services...').start();
|
|
86
86
|
try {
|
|
87
87
|
// Dnsmasq Restart
|
|
88
88
|
try {
|
package/src/commands/start.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
56
|
-
|
|
57
|
-
} catch (error) {
|
|
58
|
-
return false;
|
|
177
|
+
} else {
|
|
178
|
+
await signalProcess(pid, 'TERM', run);
|
|
59
179
|
}
|
|
60
|
-
}
|
|
61
180
|
|
|
62
|
-
|
|
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.
|
|
73
|
-
|
|
74
|
-
await
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
//
|
|
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 =
|
|
113
|
-
|
|
114
|
-
|
|
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
|
-
|
|
122
|
-
|
|
123
|
-
stdioMode = ['ignore', logStream, logStream];
|
|
284
|
+
logFd = fs.openSync(logFile, 'w');
|
|
285
|
+
stdioMode = ['ignore', logFd, logFd];
|
|
124
286
|
}
|
|
125
287
|
|
|
126
288
|
try {
|
|
127
|
-
//
|
|
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
|
-
|
|
130
|
-
|
|
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
|
-
|
|
133
|
-
|
|
134
|
-
|
|
353
|
+
try {
|
|
354
|
+
await run('caddy', ['stop']);
|
|
355
|
+
} catch {
|
|
356
|
+
/* ignore */
|
|
357
|
+
}
|
|
135
358
|
|
|
136
|
-
await
|
|
359
|
+
await run('caddy', ['start', '--config', caddyFile], { stdio: stdioMode });
|
|
137
360
|
|
|
138
361
|
if (!options.verbose) {
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
147
|
-
|
|
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
|
+
}
|
package/src/commands/stop.js
CHANGED
|
@@ -1,56 +1,84 @@
|
|
|
1
|
-
import { execa } from 'execa';
|
|
1
|
+
import { execa as defaultExeca } from 'execa';
|
|
2
2
|
import chalk from 'chalk';
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
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 =
|
|
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
|
-
|
|
14
|
-
|
|
26
|
+
spinner.stop();
|
|
27
|
+
console.log(chalk.dim('--- Verbose Logs ---'));
|
|
15
28
|
}
|
|
16
29
|
|
|
17
30
|
try {
|
|
18
|
-
|
|
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
|
|
21
|
-
} catch
|
|
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
|
|
28
|
-
} catch
|
|
29
|
-
|
|
60
|
+
await run('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
|
|
61
|
+
} catch {
|
|
62
|
+
// Ignore
|
|
30
63
|
}
|
|
31
64
|
|
|
32
65
|
if (!options.verbose) {
|
|
33
|
-
|
|
66
|
+
spinner.succeed(chalk.green('Services stopped.'));
|
|
34
67
|
} else {
|
|
35
|
-
|
|
68
|
+
console.log(chalk.green('✔ Services stopped.'));
|
|
36
69
|
}
|
|
37
70
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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(
|
|
80
|
+
console.error(
|
|
81
|
+
chalk.red(error instanceof Error ? error.message : String(error))
|
|
82
|
+
);
|
|
55
83
|
}
|
|
56
|
-
}
|
|
84
|
+
}
|
package/src/commands/unlink.js
CHANGED
|
@@ -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
|
|
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 =
|
|
25
|
+
const spinner = createSpinner(`Unlinking ${chalk.bold(targetDomain)}...`).start();
|
|
26
26
|
|
|
27
27
|
try {
|
|
28
28
|
if (!(await fs.pathExists(caddyFilePath))) {
|
package/src/lib/autostart.js
CHANGED
|
@@ -12,6 +12,9 @@ import {
|
|
|
12
12
|
} from './paths.js';
|
|
13
13
|
import { defaultExec, resolveCommand } from './exec.js';
|
|
14
14
|
|
|
15
|
+
/** Default PATH used by macOS user LaunchAgents (no Homebrew). */
|
|
16
|
+
export const LAUNCHD_MINIMAL_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';
|
|
17
|
+
|
|
15
18
|
/**
|
|
16
19
|
* Escape a string for use inside an XML plist text node.
|
|
17
20
|
* @param {string} value
|
|
@@ -25,6 +28,33 @@ export function escapeXml(value) {
|
|
|
25
28
|
.replace(/'/g, ''');
|
|
26
29
|
}
|
|
27
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Build LaunchAgent PATH: validated Homebrew bin/sbin + launchd minimal dirs.
|
|
33
|
+
* Does not inherit the interactive user environment.
|
|
34
|
+
* @param {string} brewPrefix Absolute Homebrew prefix (`brew --prefix`)
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function buildAutostartPathEnv(brewPrefix) {
|
|
38
|
+
if (typeof brewPrefix !== 'string' || brewPrefix.length === 0) {
|
|
39
|
+
throw new Error('brewPrefix is required');
|
|
40
|
+
}
|
|
41
|
+
if (!path.isAbsolute(brewPrefix)) {
|
|
42
|
+
throw new Error(`brewPrefix must be absolute (got: ${brewPrefix})`);
|
|
43
|
+
}
|
|
44
|
+
if (/[\r\n\0]/.test(brewPrefix)) {
|
|
45
|
+
throw new Error('brewPrefix must not contain control characters');
|
|
46
|
+
}
|
|
47
|
+
// `:` would split PATH entries; reject before embedding.
|
|
48
|
+
if (brewPrefix.includes(path.delimiter)) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`brewPrefix must not contain PATH delimiter (${path.delimiter})`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
const bin = path.join(brewPrefix, 'bin');
|
|
54
|
+
const sbin = path.join(brewPrefix, 'sbin');
|
|
55
|
+
return `${bin}${path.delimiter}${sbin}${path.delimiter}${LAUNCHD_MINIMAL_PATH}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
28
58
|
/**
|
|
29
59
|
* Build LaunchAgent ProgramArguments for `stagepass daemon`.
|
|
30
60
|
* @param {{ nodePath: string, cliPath: string }} paths
|
|
@@ -64,6 +94,17 @@ export function buildLaunchctlPrintArgs(uid, label = LAUNCH_AGENT_LABEL) {
|
|
|
64
94
|
return ['print', `gui/${uid}/${label}`];
|
|
65
95
|
}
|
|
66
96
|
|
|
97
|
+
/**
|
|
98
|
+
* launchctl kickstart arguments (gui domain).
|
|
99
|
+
* `-k` kills any existing instance before starting.
|
|
100
|
+
* @param {number|string} uid
|
|
101
|
+
* @param {string} [label]
|
|
102
|
+
* @returns {string[]}
|
|
103
|
+
*/
|
|
104
|
+
export function buildLaunchctlKickstartArgs(uid, label = LAUNCH_AGENT_LABEL) {
|
|
105
|
+
return ['kickstart', '-k', `gui/${uid}/${label}`];
|
|
106
|
+
}
|
|
107
|
+
|
|
67
108
|
/**
|
|
68
109
|
* Render a LaunchAgent plist that runs `stagepass daemon` at login.
|
|
69
110
|
*
|
|
@@ -72,9 +113,13 @@ export function buildLaunchctlPrintArgs(uid, label = LAUNCH_AGENT_LABEL) {
|
|
|
72
113
|
* same bind privileges as interactive `start` on macOS. If bind fails at
|
|
73
114
|
* runtime, `daemon` logs a clear error and exits 0 so KeepAlive does not loop.
|
|
74
115
|
*
|
|
116
|
+
* `pathEnv` is required so launchd (minimal PATH) can still resolve Homebrew
|
|
117
|
+
* `brew` / `caddy` by bare name without inheriting the interactive user env.
|
|
118
|
+
*
|
|
75
119
|
* @param {object} opts
|
|
76
120
|
* @param {string} opts.nodePath
|
|
77
121
|
* @param {string} opts.cliPath
|
|
122
|
+
* @param {string} opts.pathEnv Validated PATH for EnvironmentVariables
|
|
78
123
|
* @param {string} [opts.label]
|
|
79
124
|
* @param {string} [opts.stdoutPath]
|
|
80
125
|
* @param {string} [opts.stderrPath]
|
|
@@ -89,6 +134,13 @@ export function renderLaunchAgentPlist(opts) {
|
|
|
89
134
|
const stdoutPath = opts.stdoutPath || getDaemonStdoutLogPath();
|
|
90
135
|
const stderrPath = opts.stderrPath || getDaemonStderrLogPath();
|
|
91
136
|
const workingDirectory = opts.workingDirectory || os.homedir();
|
|
137
|
+
const pathEnv = opts.pathEnv;
|
|
138
|
+
if (typeof pathEnv !== 'string' || pathEnv.length === 0) {
|
|
139
|
+
throw new Error('pathEnv is required for LaunchAgent EnvironmentVariables');
|
|
140
|
+
}
|
|
141
|
+
if (/[\r\n\0]/.test(pathEnv)) {
|
|
142
|
+
throw new Error('pathEnv must not contain control characters');
|
|
143
|
+
}
|
|
92
144
|
|
|
93
145
|
const argXml = programArguments
|
|
94
146
|
.map((a) => `\t\t<string>${escapeXml(a)}</string>`)
|
|
@@ -106,6 +158,11 @@ ${argXml}
|
|
|
106
158
|
\t</array>
|
|
107
159
|
\t<key>WorkingDirectory</key>
|
|
108
160
|
\t<string>${escapeXml(workingDirectory)}</string>
|
|
161
|
+
\t<key>EnvironmentVariables</key>
|
|
162
|
+
\t<dict>
|
|
163
|
+
\t\t<key>PATH</key>
|
|
164
|
+
\t\t<string>${escapeXml(pathEnv)}</string>
|
|
165
|
+
\t</dict>
|
|
109
166
|
\t<key>RunAtLoad</key>
|
|
110
167
|
\t<true/>
|
|
111
168
|
\t<key>KeepAlive</key>
|
|
@@ -220,6 +277,228 @@ export async function resolveAutostartPaths(opts = {}) {
|
|
|
220
277
|
return { ok: true, nodePath, cliPath: cliCheck.path, error: null };
|
|
221
278
|
}
|
|
222
279
|
|
|
280
|
+
/**
|
|
281
|
+
* True when `absolutePath` is the Homebrew prefix or a path beneath it.
|
|
282
|
+
* @param {string} absolutePath
|
|
283
|
+
* @param {string} brewPrefix
|
|
284
|
+
*/
|
|
285
|
+
function isPathUnderPrefix(absolutePath, brewPrefix) {
|
|
286
|
+
return (
|
|
287
|
+
absolutePath === brewPrefix ||
|
|
288
|
+
absolutePath.startsWith(`${brewPrefix}${path.sep}`)
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Validate a tool as launchd will see it: the PATH shim must live in
|
|
294
|
+
* `prefix/bin` or `prefix/sbin`. The realpath target may be under Cellar
|
|
295
|
+
* (normal Homebrew layout) but must remain under the same prefix, be a
|
|
296
|
+
* regular file, and be executable.
|
|
297
|
+
*
|
|
298
|
+
* @param {object} opts
|
|
299
|
+
* @param {string} opts.name
|
|
300
|
+
* @param {string} opts.shimPath Absolute path returned by `which` / PATH lookup
|
|
301
|
+
* @param {string} opts.brewPrefix
|
|
302
|
+
* @param {(p: string) => Promise<string>} opts.realpath
|
|
303
|
+
* @param {(p: string) => Promise<boolean>} opts.pathExists
|
|
304
|
+
* @param {(p: string) => Promise<import('node:fs').Stats>} opts.stat
|
|
305
|
+
* @returns {Promise<{ ok: true, path: string, canonicalPath: string } | { ok: false, error: string }>}
|
|
306
|
+
*/
|
|
307
|
+
async function validatePrefixPathTool(opts) {
|
|
308
|
+
const { name, shimPath, brewPrefix, realpath, pathExists, stat } = opts;
|
|
309
|
+
const shimCheck = await requireAbsoluteExistingPath(shimPath, name, pathExists);
|
|
310
|
+
if (!shimCheck.ok) return shimCheck;
|
|
311
|
+
|
|
312
|
+
const prefixBin = path.join(brewPrefix, 'bin');
|
|
313
|
+
const prefixSbin = path.join(brewPrefix, 'sbin');
|
|
314
|
+
const shimDir = path.dirname(shimCheck.path);
|
|
315
|
+
if (shimDir !== prefixBin && shimDir !== prefixSbin) {
|
|
316
|
+
return {
|
|
317
|
+
ok: false,
|
|
318
|
+
error: `${name} PATH entry must be in ${prefixBin} or ${prefixSbin} (got ${shimDir}).`,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
let canonicalPath;
|
|
323
|
+
try {
|
|
324
|
+
canonicalPath = await realpath(shimCheck.path);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
return {
|
|
327
|
+
ok: false,
|
|
328
|
+
error: `Could not realpath ${name} at ${shimCheck.path}: ${
|
|
329
|
+
error instanceof Error ? error.message : String(error)
|
|
330
|
+
}`,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (!isPathUnderPrefix(canonicalPath, brewPrefix)) {
|
|
335
|
+
return {
|
|
336
|
+
ok: false,
|
|
337
|
+
error: `${name} realpath (${canonicalPath}) is not under brew --prefix (${brewPrefix}).`,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
let st;
|
|
342
|
+
try {
|
|
343
|
+
st = await stat(canonicalPath);
|
|
344
|
+
} catch (error) {
|
|
345
|
+
return {
|
|
346
|
+
ok: false,
|
|
347
|
+
error: `Could not stat ${name} at ${canonicalPath}: ${
|
|
348
|
+
error instanceof Error ? error.message : String(error)
|
|
349
|
+
}`,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
if (!st.isFile()) {
|
|
353
|
+
return {
|
|
354
|
+
ok: false,
|
|
355
|
+
error: `${name} resolves to a non-file: ${canonicalPath}`,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
if (!(st.mode & 0o111)) {
|
|
359
|
+
return {
|
|
360
|
+
ok: false,
|
|
361
|
+
error: `${name} is not executable: ${canonicalPath}`,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return { ok: true, path: shimCheck.path, canonicalPath };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Resolve Homebrew + Caddy for the LaunchAgent runtime environment.
|
|
370
|
+
* Uses the interactive enable-time PATH to locate tools, then records a
|
|
371
|
+
* launchd-safe PATH from the validated `brew --prefix` (Apple Silicon
|
|
372
|
+
* `/opt/homebrew` or Intel `/usr/local` via brew itself — not hardcoded).
|
|
373
|
+
*
|
|
374
|
+
* PATH shims must sit in `prefix/bin` or `prefix/sbin`. Realpaths may point
|
|
375
|
+
* into `Cellar/...` (standard Homebrew) as long as they stay under the prefix.
|
|
376
|
+
*
|
|
377
|
+
* @param {object} [opts]
|
|
378
|
+
* @param {import('./exec.js').ExecFn} [opts.exec]
|
|
379
|
+
* @param {(p: string) => Promise<string>} [opts.realpath]
|
|
380
|
+
* @param {(p: string) => Promise<boolean>} [opts.pathExists]
|
|
381
|
+
* @param {(p: string) => Promise<import('node:fs').Stats>} [opts.stat]
|
|
382
|
+
* @returns {Promise<{
|
|
383
|
+
* ok: boolean,
|
|
384
|
+
* error?: string,
|
|
385
|
+
* brewPath?: string,
|
|
386
|
+
* caddyPath?: string,
|
|
387
|
+
* brewPrefix?: string,
|
|
388
|
+
* pathEnv?: string,
|
|
389
|
+
* }>}
|
|
390
|
+
*/
|
|
391
|
+
export async function resolveAutostartRuntimeEnvironment(opts = {}) {
|
|
392
|
+
const exec = opts.exec || defaultExec;
|
|
393
|
+
const realpath =
|
|
394
|
+
opts.realpath || ((p) => fs.realpath(p).then((r) => String(r)));
|
|
395
|
+
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
396
|
+
const stat = opts.stat || ((p) => fs.stat(p));
|
|
397
|
+
|
|
398
|
+
const brewWhich = await resolveCommand('brew', exec);
|
|
399
|
+
if (!brewWhich) {
|
|
400
|
+
return {
|
|
401
|
+
ok: false,
|
|
402
|
+
error:
|
|
403
|
+
'Homebrew `brew` not found. Install Homebrew and ensure it is on PATH before enabling autostart.',
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
const brewShim = path.resolve(brewWhich);
|
|
407
|
+
const brewShimCheck = await requireAbsoluteExistingPath(
|
|
408
|
+
brewShim,
|
|
409
|
+
'brew',
|
|
410
|
+
pathExists
|
|
411
|
+
);
|
|
412
|
+
if (!brewShimCheck.ok) {
|
|
413
|
+
return { ok: false, error: brewShimCheck.error };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
let brewPrefix = '';
|
|
417
|
+
try {
|
|
418
|
+
// Invoke via the PATH shim (not Cellar realpath) — matches user `brew --prefix`.
|
|
419
|
+
const { stdout } = await exec(brewShimCheck.path, ['--prefix']);
|
|
420
|
+
brewPrefix = String(stdout || '').trim();
|
|
421
|
+
} catch (error) {
|
|
422
|
+
return {
|
|
423
|
+
ok: false,
|
|
424
|
+
error: `Could not read Homebrew prefix via brew --prefix: ${
|
|
425
|
+
error instanceof Error ? error.message : String(error)
|
|
426
|
+
}`,
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (!brewPrefix || !path.isAbsolute(brewPrefix) || /[\r\n\0]/.test(brewPrefix)) {
|
|
431
|
+
return {
|
|
432
|
+
ok: false,
|
|
433
|
+
error: `Invalid Homebrew prefix from brew --prefix: ${brewPrefix || '(empty)'}`,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
if (brewPrefix.includes(path.delimiter)) {
|
|
437
|
+
return {
|
|
438
|
+
ok: false,
|
|
439
|
+
error: `Homebrew prefix contains PATH delimiter: ${brewPrefix}`,
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const prefixBin = path.join(brewPrefix, 'bin');
|
|
444
|
+
if (!(await pathExists(prefixBin))) {
|
|
445
|
+
return {
|
|
446
|
+
ok: false,
|
|
447
|
+
error: `Homebrew prefix bin directory does not exist: ${prefixBin}`,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const brewTool = await validatePrefixPathTool({
|
|
452
|
+
name: 'brew',
|
|
453
|
+
shimPath: brewShimCheck.path,
|
|
454
|
+
brewPrefix,
|
|
455
|
+
realpath,
|
|
456
|
+
pathExists,
|
|
457
|
+
stat,
|
|
458
|
+
});
|
|
459
|
+
if (!brewTool.ok) {
|
|
460
|
+
return { ok: false, error: brewTool.error };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const caddyWhich = await resolveCommand('caddy', exec);
|
|
464
|
+
if (!caddyWhich) {
|
|
465
|
+
return {
|
|
466
|
+
ok: false,
|
|
467
|
+
error:
|
|
468
|
+
'Caddy not found. Run `stagepass setup` (or `brew install caddy`) before enabling autostart.',
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
const caddyTool = await validatePrefixPathTool({
|
|
472
|
+
name: 'caddy',
|
|
473
|
+
shimPath: path.resolve(caddyWhich),
|
|
474
|
+
brewPrefix,
|
|
475
|
+
realpath,
|
|
476
|
+
pathExists,
|
|
477
|
+
stat,
|
|
478
|
+
});
|
|
479
|
+
if (!caddyTool.ok) {
|
|
480
|
+
return { ok: false, error: caddyTool.error };
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
let pathEnv;
|
|
484
|
+
try {
|
|
485
|
+
pathEnv = buildAutostartPathEnv(brewPrefix);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
return {
|
|
488
|
+
ok: false,
|
|
489
|
+
error: error instanceof Error ? error.message : String(error),
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return {
|
|
494
|
+
ok: true,
|
|
495
|
+
brewPath: brewTool.path,
|
|
496
|
+
caddyPath: caddyTool.path,
|
|
497
|
+
brewPrefix,
|
|
498
|
+
pathEnv,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
223
502
|
/**
|
|
224
503
|
* @param {object} [opts]
|
|
225
504
|
* @param {import('./exec.js').ExecFn} [opts.exec]
|
|
@@ -264,6 +543,7 @@ export async function getAutostartStatus(opts = {}) {
|
|
|
264
543
|
export async function enableAutostart(opts = {}) {
|
|
265
544
|
const exec = opts.exec || defaultExec;
|
|
266
545
|
const uid = opts.uid ?? process.getuid?.() ?? os.userInfo().uid;
|
|
546
|
+
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
267
547
|
const paths =
|
|
268
548
|
opts.paths ||
|
|
269
549
|
(await resolveAutostartPaths({
|
|
@@ -271,7 +551,7 @@ export async function enableAutostart(opts = {}) {
|
|
|
271
551
|
argv1: opts.argv1,
|
|
272
552
|
exec,
|
|
273
553
|
realpath: opts.realpath,
|
|
274
|
-
pathExists
|
|
554
|
+
pathExists,
|
|
275
555
|
}));
|
|
276
556
|
|
|
277
557
|
if (!paths.ok) {
|
|
@@ -285,7 +565,6 @@ export async function enableAutostart(opts = {}) {
|
|
|
285
565
|
error: 'Autostart nodePath and cliPath must be absolute.',
|
|
286
566
|
};
|
|
287
567
|
}
|
|
288
|
-
const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
|
|
289
568
|
if (!(await pathExists(paths.nodePath)) || !(await pathExists(paths.cliPath))) {
|
|
290
569
|
return {
|
|
291
570
|
ok: false,
|
|
@@ -293,18 +572,36 @@ export async function enableAutostart(opts = {}) {
|
|
|
293
572
|
};
|
|
294
573
|
}
|
|
295
574
|
|
|
575
|
+
const runtime =
|
|
576
|
+
opts.runtime ||
|
|
577
|
+
(await resolveAutostartRuntimeEnvironment({
|
|
578
|
+
exec,
|
|
579
|
+
realpath: opts.realpath,
|
|
580
|
+
pathExists,
|
|
581
|
+
}));
|
|
582
|
+
if (!runtime.ok || !runtime.pathEnv) {
|
|
583
|
+
return {
|
|
584
|
+
ok: false,
|
|
585
|
+
error:
|
|
586
|
+
runtime.error ||
|
|
587
|
+
'Could not resolve Homebrew/Caddy paths for LaunchAgent PATH.',
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
296
591
|
const plistPath = opts.plistPath || getLaunchAgentPlistPath();
|
|
297
592
|
const agentsDir = path.dirname(plistPath);
|
|
298
593
|
const ensureDir = opts.ensureDir || ((p) => fs.ensureDir(p));
|
|
299
594
|
const writeFile = opts.writeFile || ((p, c) => fs.writeFile(p, c, 'utf8'));
|
|
300
595
|
const logsDir = opts.logsDir || getLogsDir();
|
|
301
596
|
|
|
597
|
+
// Write only after node/cli + Homebrew/Caddy prerequisites validate.
|
|
302
598
|
await ensureDir(agentsDir);
|
|
303
599
|
await ensureDir(logsDir);
|
|
304
600
|
|
|
305
601
|
const plist = renderLaunchAgentPlist({
|
|
306
602
|
nodePath: paths.nodePath,
|
|
307
603
|
cliPath: paths.cliPath,
|
|
604
|
+
pathEnv: runtime.pathEnv,
|
|
308
605
|
stdoutPath: opts.stdoutPath || getDaemonStdoutLogPath(),
|
|
309
606
|
stderrPath: opts.stderrPath || getDaemonStderrLogPath(),
|
|
310
607
|
workingDirectory: opts.workingDirectory || os.homedir(),
|
|
@@ -330,7 +627,7 @@ export async function enableAutostart(opts = {}) {
|
|
|
330
627
|
};
|
|
331
628
|
}
|
|
332
629
|
|
|
333
|
-
return { ok: true, plistPath, paths, error: null };
|
|
630
|
+
return { ok: true, plistPath, paths, runtime, error: null };
|
|
334
631
|
}
|
|
335
632
|
|
|
336
633
|
/**
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import ora from 'ora';
|
|
2
|
+
|
|
3
|
+
const FALLBACK_COLUMNS = 80;
|
|
4
|
+
const FALLBACK_ROWS = 24;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Ora uses `stream.columns ?? 80`; a literal `0` bypasses that fallback and
|
|
8
|
+
* yields Infinity line clears (runaway ANSI). Floor first so values in (0,1)
|
|
9
|
+
* cannot become 0 after Math.floor and re-enter the unsafe path.
|
|
10
|
+
* @param {unknown} columns
|
|
11
|
+
* @param {number} [fallback]
|
|
12
|
+
* @returns {number}
|
|
13
|
+
*/
|
|
14
|
+
export function resolveSpinnerColumns(columns, fallback = FALLBACK_COLUMNS) {
|
|
15
|
+
if (typeof columns !== 'number' || !Number.isFinite(columns)) return fallback;
|
|
16
|
+
const width = Math.floor(columns);
|
|
17
|
+
return width > 0 ? width : fallback;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {unknown} rows
|
|
22
|
+
* @param {number} [fallback]
|
|
23
|
+
* @returns {number}
|
|
24
|
+
*/
|
|
25
|
+
export function resolveSpinnerRows(rows, fallback = FALLBACK_ROWS) {
|
|
26
|
+
if (typeof rows !== 'number' || !Number.isFinite(rows)) return fallback;
|
|
27
|
+
const value = Math.floor(rows);
|
|
28
|
+
return value > 0 ? value : fallback;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Always wrap: TTY geometry can change after spinner creation (e.g. 80→0).
|
|
33
|
+
* @param {NodeJS.WritableStream & { columns?: number, rows?: number, isTTY?: boolean }} stream
|
|
34
|
+
*/
|
|
35
|
+
export function withSafeGeometry(stream) {
|
|
36
|
+
return new Proxy(stream, {
|
|
37
|
+
get(target, prop, receiver) {
|
|
38
|
+
if (prop === 'columns') return resolveSpinnerColumns(target.columns);
|
|
39
|
+
if (prop === 'rows') return resolveSpinnerRows(target.rows);
|
|
40
|
+
const value = Reflect.get(target, prop, receiver);
|
|
41
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Create an ora spinner that never treats TTY width 0/NaN/Infinity as valid.
|
|
48
|
+
* Positive finite TTY geometry stays positive; live resizes are re-checked.
|
|
49
|
+
* @param {string} [text]
|
|
50
|
+
* @param {import('ora').Options} [options]
|
|
51
|
+
*/
|
|
52
|
+
export function createSpinner(text = '', options = {}) {
|
|
53
|
+
const stream = options.stream ?? process.stderr;
|
|
54
|
+
const safeStream = withSafeGeometry(stream);
|
|
55
|
+
return ora({
|
|
56
|
+
...options,
|
|
57
|
+
text,
|
|
58
|
+
stream: safeStream,
|
|
59
|
+
});
|
|
60
|
+
}
|
package/src/lib/versions.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* `stagepass upgrade` only writes ranges a published version satisfies.
|
|
7
7
|
* A monorepo test keeps this in sync with packages/loader and packages/modules.
|
|
8
8
|
*/
|
|
9
|
-
export const STAGEPASS_PACKAGES_VERSION = '2.2.
|
|
9
|
+
export const STAGEPASS_PACKAGES_VERSION = '2.2.2';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Major caret range for a version (e.g. 2.2.0 → ^2), matching the `@2` CDN
|