@stagepass/cli 2.3.1 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +55 -15
  2. package/package.json +1 -1
  3. package/src/cli.js +48 -5
  4. package/src/commands/dev.js +14 -0
  5. package/src/commands/link.js +11 -1
  6. package/src/commands/new.js +39 -16
  7. package/src/commands/npm-run.js +14 -0
  8. package/src/commands/reload.js +5 -1
  9. package/src/commands/start.js +1 -1
  10. package/src/commands/upgrade.js +103 -32
  11. package/src/lib/build-script-upgrade.js +249 -0
  12. package/src/lib/caddy-version.js +31 -0
  13. package/src/lib/caddyfile.js +76 -36
  14. package/src/lib/doctor-site.js +15 -10
  15. package/src/lib/doctor.js +30 -29
  16. package/src/lib/htaccess-upgrade.js +79 -0
  17. package/src/lib/migrate.js +29 -2
  18. package/src/lib/package-versions.js +1 -1
  19. package/src/lib/php-runtime.js +249 -0
  20. package/src/lib/scaffold.js +24 -16
  21. package/templates/project/README.md.tmpl +8 -6
  22. package/templates/project/api/README.md.tmpl +206 -5
  23. package/templates/project/api/action.php +103 -0
  24. package/templates/project/api/actions/boom.php +21 -0
  25. package/templates/project/api/actions/contact.php +46 -0
  26. package/templates/project/api/actions/ping.php +23 -0
  27. package/templates/project/api/actions.php +59 -0
  28. package/templates/project/api/env.example +25 -0
  29. package/templates/project/api/lib/bootstrap.php +44 -0
  30. package/templates/project/api/lib/config.php +179 -0
  31. package/templates/project/api/lib/request.php +94 -0
  32. package/templates/project/api/lib/response.php +97 -0
  33. package/templates/project/api/lib/security.php +114 -0
  34. package/templates/project/api/lib/validate.php +69 -0
  35. package/templates/project/gitignore +4 -0
  36. package/templates/project/htaccess +7 -0
  37. package/templates/project/php-private/config.php +24 -0
  38. package/templates/project/scripts/build.mjs +128 -8
  39. package/templates/project/examples/php/README.md.tmpl +0 -18
  40. package/templates/project/examples/php/form.php +0 -105
  41. package/templates/project/examples/php/proxy.php +0 -171
package/README.md CHANGED
@@ -6,7 +6,7 @@ The CLI sets up and manages the local Stagepass infrastructure (`.sp` domains, C
6
6
 
7
7
  ## Install
8
8
 
9
- Published CLI 2.3.0 requires Node.js **20.17+** (`engines.node`: `>=20.17.0`) on **macOS** with Homebrew, because `@inquirer/prompts@8` requires it. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18. Development and CI use Node 22 or 24.
9
+ Published CLI 2.4.0 requires Node.js **20.17+** (`engines.node`: `>=20.17.0`) on **macOS** with Homebrew, because `@inquirer/prompts@8` requires it. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18. Development and CI use Node 22 or 24.
10
10
 
11
11
  ```bash
12
12
  npm install -g @stagepass/cli@2
@@ -21,7 +21,7 @@ npx @stagepass/cli@2 setup
21
21
  ## Requirements
22
22
 
23
23
  - **macOS** (system commands refuse other platforms with exit code 1; this is not a breaking change because those commands never worked off macOS)
24
- - Published CLI 2.3.0: Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
24
+ - Published CLI 2.4.0: Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
25
25
  - Homebrew
26
26
 
27
27
  `stagepass --version` and `stagepass --help` work on any platform. For tests/CI only, set `STAGEPASS_SKIP_PLATFORM_CHECK=1` to bypass the macOS guard (not for production use).
@@ -51,12 +51,12 @@ Linked: https://my-project.sp -> /absolute/path/to/project
51
51
  | Command | Description |
52
52
  | :--- | :--- |
53
53
  | `stagepass setup` | Install Caddy, PHP, Dnsmasq via Homebrew and configure the local `.sp` resolver (`address=/.sp/127.0.0.1` + `/etc/resolver/sp`). |
54
- | `stagepass start` | Start Caddy & PHP. Runs `certs check` (offers repair when interactive). No unconditional root warm-up: inspects port 443 without sudo; signals only after confirm (TERM then optional KILL; sudo only if unprivileged kill fails). With autostart installed, bootstraps/kickstarts the LaunchAgent (else direct `caddy start`). Migrates legacy Caddyfile blocks if needed. |
55
- | `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. |
54
+ | `stagepass start` | Start Caddy & PHP. Runs `certs check` (offers repair when interactive). No unconditional root warm-up: inspects port 443 without sudo; signals only after confirm (TERM then optional KILL; sudo only if unprivileged kill fails). With autostart installed, bootstraps/kickstarts the LaunchAgent (else direct `caddy start`). Migrates legacy Caddyfile blocks if needed, except when Caddy is known to be older than 2.9 (`brew upgrade caddy`). |
55
+ | `stagepass link [domain]` | Link the current directory to a `.sp` domain, write/update the Caddyfile + `~/.stagepass/projects.json`, reload Caddy. The linked block is v3. On Caddy older than 2.9, other existing blocks are left unchanged and CORS on success responses may be missing (`brew upgrade caddy`). |
56
56
  | `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
57
- | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed. |
57
+ | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed, except when Caddy is known to be older than 2.9 (`brew upgrade caddy`). |
58
58
  | `stagepass stop` | Stop Caddy & PHP. If autostart is installed/loaded, `launchctl bootout` first (until next login); use `autostart off` to disable permanently. |
59
- | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files. Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
59
+ | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files. Reports the Caddy version and warns (does not fail) when it is older than 2.9 (`brew upgrade caddy`); the v3 site block needs 2.9 or newer. Published CLI 2.3.1 and later fails when a LaunchAgent node or CLI path is missing, and warns on a versioned Homebrew Cellar node path or a daemon version that differs from the CLI (fix hint: `stagepass autostart on`). Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
60
60
  | `stagepass certs check` | Read-only Caddy local CA check (validity, System keychain trust, orphans, optional TLS handshake per linked domain). `--json`, `--skip-handshake`. |
61
61
  | `stagepass certs trust` | Run `caddy trust` after interactive confirmation (or `--yes`). |
62
62
  | `stagepass certs renew` | Repair failing linked site certs; `--root` moves the CA folder to a backup (double confirm, or `--yes --i-understand-root-renewal`); `--remove-orphans` deletes keychain orphans by SHA-1 after confirm. |
@@ -66,7 +66,7 @@ Linked: https://my-project.sp -> /absolute/path/to/project
66
66
  | `stagepass build` | Run `npm run build` in the current project (forwards exit code). |
67
67
  | `stagepass watch` | Run `npm run watch` in the current project (forwards exit code). If Stagepass is not running, asks to start it (TTY) or prints a `stagepass start` hint (non-TTY / CI); warns with `stagepass link` when the cwd is not linked. |
68
68
  | `stagepass dev` | Like `stagepass watch`, plus live reload on the linked `.sp` domain (CSS can swap without a full reload). Same running check as watch; requires `stagepass link` (hard error if unlinked). |
69
- | `stagepass upgrade` | Bump `@stagepass/*`, sync declared modules, `AGENTS.md`, the Cursor rule and `types`, print Webflow snippets. |
69
+ | `stagepass upgrade` | Bump `@stagepass/*`, sync declared modules, `AGENTS.md`, the Cursor rule and `types`, print Webflow snippets. Since 2.4.1, writes a missing PHP `.htaccess` when `"php": true`. |
70
70
 
71
71
  All commands support `-v, --verbose` where applicable.
72
72
 
@@ -77,7 +77,8 @@ All commands support `-v, --verbose` where applicable.
77
77
  - `certs renew` is opt-in and confirmation-gated. Site repair only deletes `certificates/local/<linked-domain>` after checks fail. `--root` moves the CA folder to a timestamped backup (never deletes; needs two interactive confirmations without `--yes`, or `--yes --i-understand-root-renewal`). `--yes` alone always aborts for `--root` (TTY or not). Do not combine `--root` with `--remove-orphans`; run them as separate commands. Orphans are removed only by SHA-1 via `renew --remove-orphans`.
78
78
  - Chrome may require Local Network Access permission for public HTTPS pages that load `https://*.sp` assets.
79
79
  - 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, may notify, and exits `0` so launchd KeepAlive does not restart-loop. Interactive `start` confirms before signalling any non-caddy listener (name + PID; SIGTERM then optional SIGKILL). Own processes are signalled without elevated rights first; `sudo` only when needed after confirmation. There is no standby `sudo -v`.
80
- - `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.
80
+ - `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. Published CLI 2.3.1 and later uses the Homebrew `bin/node` shim when the running node is a versioned Cellar path.
81
+ - Published CLI 2.3.1 and later `stagepass doctor` fails when a LaunchAgent node or CLI path is missing. It warns when that node path is a versioned Homebrew Cellar path, or when the running daemon version differs from the CLI. The fix hint is `stagepass autostart on`.
81
82
  - Published CLI requires Node `>=20.17.0`. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18.
82
83
  - Manual macOS checklist: [`TESTING-macos.md`](./TESTING-macos.md).
83
84
 
@@ -94,7 +95,7 @@ These are different prompts. Grant only the narrow dialog macOS shows. Stagepass
94
95
  #### Install location and LaunchAgent paths
95
96
 
96
97
  - 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.
97
- - `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.
98
+ - `autostart on` records **absolute** Node and CLI paths plus the validated Homebrew `PATH`. Published CLI 2.3.1 and later uses the Homebrew `bin/node` shim when the running node is a versioned Cellar path (it does not store that versioned binary). It does not follow later `brew` upgrades automatically.
98
99
  - 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.
99
100
  - 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.
100
101
  - Development checkouts (`packages/cli`, Desktop test packs) and the published global install are different binaries; compare behaviour with one style at a time.
@@ -114,8 +115,8 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
114
115
  | `--staging <domain>` | Staging hostname (hostname only; same validation as `--origin`). Stored as `origin`. Must match `--site` when both are set. |
115
116
  | `--production <domain>` | Optional production hostname. Stored as `production`. When omitted, prints a short hint to add it later via `stagepass link --origin`. |
116
117
  | `--site-modules <list>` | Modules the site loads: `none`, `all`, or a comma list of `inject`, `cookies`, `maintenance`. Takes precedence over `--site`. |
117
- | `--php` / `--no-php` | Enable PHP for the project (`api/` + `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
118
- | `--php-examples` / `--no-php-examples` | Include `examples/php/` samples (requires `--php`). Default: off. |
118
+ | `--php` / `--no-php` | Enable the PHP boilerplate (`api/`, `.php/config.php`, `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
119
+ | `--php-examples` / `--no-php-examples` | Deprecated. Sample actions ship with `--php` in `api/actions/`. The flags are accepted and do not copy a second sample set. |
119
120
  | `--link` / `--no-link` | After scaffolding, run `stagepass link` (macOS only). Default: off; interactive macOS may offer it. |
120
121
  | `--git` / `--no-git` | `git init` (default: yes). |
121
122
  | `--remote <url>` | Set `origin` after git init (rejects URLs with embedded credentials). |
@@ -125,7 +126,39 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
125
126
 
126
127
  The name must be DNS-safe (lowercase `a-z`, `0-9`, hyphens; 1 to 63 chars; no leading/trailing hyphen). Existing files are never overwritten. Generated projects include `scripts/build.mjs` (content-hashed `dist/` + SRI `integrity` in `manifest.json`), scripts `build` / `watch` / `dev` (`dev` aliases `watch`), Webflow head/footer snippets (jsDelivr `@2`, loader plus the declared modules), `stagepass.json`, an `AGENTS.md` with the full `sp` API reference, `.cursor/rules/stagepass.mdc`, and a `.gitignore`. `@stagepass/loader` / `@stagepass/modules` are added as `^2` (same major as the CDN pin `@2`; npm installs the newest published 2.x). Per-module types are written only when the published or installed `@stagepass/modules` ships them (2.2.0 and later); otherwise `types` lists the umbrella `@stagepass/modules`.
127
128
 
128
- Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). Without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. Staging / production prompts, PHP prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are part of this release.
129
+ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). Without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. The interactive wizard always asks whether to enable PHP unless `--php` / `--no-php` was passed. Staging / production prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are part of this release.
130
+
131
+ ### PHP
132
+
133
+ `--php` writes a plain PHP 8.2 boilerplate: `api/action.php` is the only public entry, actions are an allowlist in `api/actions.php`, and `.php/config.php` sits in the same folder as `api/`. That folder is the document root (the project root locally, `dist/` after `stagepass build`). Copy `api/.env.example` to `.env` in the project root (or use `.php/.env`) and set `ALLOWED_ORIGINS` (include `https://<name>.sp`). There is no mail. `load_config()` reads that project-root `.env` and `.php/.env`. It never reads `api/.env`.
134
+
135
+ Caddy already returns 404 for any path segment that starts with `.` (`/.env`, `/api/.env`, `/.php/`). Since 2.4.1, `stagepass new --php` ships a web-root `.htaccess` with the Apache rule below, and `stagepass build` copies it into `dist/` when the project has one. Published CLI 2.4.0 does not ship that file. `stagepass new` refuses to overwrite an existing `.htaccess`. nginx does not read `.htaccess`; add the snippet below in the server block before `location ~ \.php$`. Prefer real environment variables so a `.env` file is not required in the web root.
136
+
137
+ `stagepass new` and `doctor` warn when `php` is missing, older than 8.2, or has no `php-fpm` / `php-cgi` (`brew install php` on macOS). `stagepass dev` and `stagepass watch` on a `"php": true` project do the same check and start Homebrew php-fpm (`brew services start php`, and `brew services restart php` only if start fails), the same helper `stagepass start` has used since 2.3. The JS build still runs. `stagepass build` copies `api/` to `dist/api/`, `.php/config.php` to `dist/.php/config.php`, and a project-root `.htaccess` to `dist/.htaccess` when `"php": true` and the file exists. It does not copy `.env`, `.php/.env`, or `.php/rate-limit/`. The copy also skips logs, pid files, and key, certificate, or database files (`.pem`, `.key`, `.p12`, `.pfx`, `.crt`, `.cer`, `.sqlite`, `.db`). It keeps `.htaccess` and `.env.example`. A `dist/.htaccess` already on disk stays when the project has none. Upload `dist/` (the folder that contains `api/`). That folder is the web root, so `.php/` is public on Apache and nginx unless hidden paths are denied. The public URL stays `/api/action.php`.
138
+
139
+ Apache, in the web root `.htaccess`. `AllowOverride All` and `mod_rewrite` are required. The rule follows HTML5 Boilerplate [`file_access.conf`](https://github.com/h5bp/server-configs-apache/blob/main/h5bp/security/file_access.conf), wrapped in `IfModule`:
140
+
141
+ ```apache
142
+ <IfModule mod_rewrite.c>
143
+ RewriteEngine On
144
+ RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
145
+ RewriteCond %{SCRIPT_FILENAME} -d [OR]
146
+ RewriteCond %{SCRIPT_FILENAME} -f
147
+ RewriteRule "(^|/)\." - [F]
148
+ </IfModule>
149
+ ```
150
+
151
+ nginx, inside the server block, before the PHP `location ~ \.php$` block. If this location comes later, `/.php/config.php` can be passed to php-fpm. The rule follows HTML5 Boilerplate [`security_file_access.conf`](https://github.com/h5bp/server-configs-nginx/blob/main/h5bp/location/security_file_access.conf):
152
+
153
+ ```nginx
154
+ location ~* /\.(?!well-known\/) {
155
+ deny all;
156
+ }
157
+ ```
158
+
159
+ Both rules were tested on 12 November 2026 on php:8.2-apache (`AllowOverride All`, `a2enmod rewrite`) and on nginx 1.27 with php:8.2-fpm. `/.env`, `/.php/config.php`, `/api/.env.example`, and `/.git/HEAD` returned HTTP 403, with no secret or config leak. `/api/action.php?action=ping` returned HTTP 200, `{"status":"success","data":{"pong":true},"message":null}`. `/.well-known/test.txt` returned HTTP 200, body `well-known-ok`. `/.well-known/` as a directory with no index file returned HTTP 403 on both servers (no DirectoryIndex). Visible files under `/.well-known/` stay reachable. Published CLI 2.4.0 still needs these rules added by hand. Since 2.4.1 the Apache rule ships in the PHP scaffold, and `stagepass upgrade` writes a missing project `.htaccess` when `"php": true` ([quYArF43](https://trello.com/c/quYArF43)). nginx still needs the snippet on the host.
160
+
161
+ `stagepass dev` / `watch` serve PHP from the project root, so edits show up on the next request. From the folder that contains `api/`, `php -S 127.0.0.1:8080 -t .` matches `/api/action.php`. `php -S` does not apply Caddy's hidden-path 404. Do not point it at a folder that already contains a real `.env`. Prefer `stagepass dev` or the linked `.sp` domain. `sp.resolveLocalUrl` returns a URL only during an active `.sp` session. On Webflow, `window.location.origin` is the Webflow host, which does not run PHP. Fetch the absolute PHP host, for example `https://php.example.com/api/action.php`. `rate_limit_allows()` is fail-open and `client_ip()` uses only `REMOTE_ADDR`, never `X-Forwarded-For` (do not trust that header without a proxy allowlist). Behind a reverse proxy every visitor can share one counter. Still open: [sgt7wKlT](https://trello.com/c/sgt7wKlT). `stagepass upgrade` does not add the `api/` or `.php/` boilerplate. When `"php": true` and the project root has no `.htaccess`, it writes the shipped template (same bytes as `stagepass new --php`). An existing `.htaccess` is left unchanged. If that file has no `RewriteRule "(^|/)\." - [F]` line, upgrade prints a hint and still exits 0. Published CLI 2.4.0 does not write that file. The website guide is live at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/) (source outline: [docs/php.md](https://github.com/arobertherz/stagepass/blob/master/docs/php.md)).
129
162
 
130
163
  ### Declared modules (`stagepass.json`)
131
164
 
@@ -137,7 +170,7 @@ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `
137
170
 
138
171
  - the managed block in `AGENTS.md` (between `<!-- stagepass:begin -->` and `<!-- stagepass:end -->`): loader API always, full sections for declared modules, a "not available; enable by …" line for the others, and the rule never to use undeclared `sp.<module>`;
139
172
  - `.cursor/rules/stagepass.mdc` (globs `src/**`) with the same content;
140
- - `compilerOptions.types` in `tsconfig.json` / `jsconfig.json`: `@stagepass/loader` plus `@stagepass/modules/<module>` for each declared module (`@stagepass/modules` for `all`), so undeclared modules are type errors.
173
+ - `compilerOptions.types` in `tsconfig.json` / `jsconfig.json`: `@stagepass/loader` plus `@stagepass/modules/<module>` for each declared module (`@stagepass/modules` for `all`), so undeclared modules are type errors. Published `@stagepass/loader` 2.5.0 `global.d.ts` augments `Window` with `sp` and `stagepass` (both `StagepassAPI`) and declares global `var sp` / `var stagepass`. The scaffold `src/main.ts` still narrows `sp` to `log` for the ready line. The official types are wider.
141
174
 
142
175
  The legacy boolean `"modules": true|false` is still read; `upgrade` replaces it with a list (`true` becomes `["all"]` without a TTY).
143
176
 
@@ -158,7 +191,7 @@ Still not recognised: tags without `src`, `data-src` only, other hosts without a
158
191
  | `--site <host>` | Live site to detect modules from (default: the origin linked in `~/.stagepass/projects.json` for this folder). Stored in `stagepass.json` when given. |
159
192
  | `--site-modules <list>` | Set the modules list directly (`none`, `all`, or a comma list). |
160
193
  | `--skip-site` | Do not fetch the live site. |
161
- | `-y, --yes` | Accept the detected or existing list without asking. |
194
+ | `-y, --yes` | Accept the detected or existing list without asking. With `--yes`, CLI 2.4.0 also replaces an unmodified `scripts/build.mjs`. |
162
195
  | `--dry-run` | Print every planned change; write no file. |
163
196
 
164
197
  `upgrade` bumps `@stagepass/*` in `package.json`, then resolves the modules list (`--site-modules`, else live detection, confirmed interactively; if the site is unreachable or no origin is known it asks; without a TTY it keeps the existing list or `[]` and prints a hint). It then syncs the project:
@@ -167,6 +200,8 @@ Still not recognised: tags without `src`, `data-src` only, other hosts without a
167
200
  - `AGENTS.md`: created if missing, otherwise only the managed block is replaced (or appended when there is none). Your own text stays. Broken markers are left alone with a hint.
168
201
  - `.cursor/rules/stagepass.mdc`: created if missing, otherwise only its managed block is refreshed.
169
202
  - `tsconfig.json` / `jsconfig.json`: only `compilerOptions.types` changes, the rest of the JSON is preserved. Files with comments, or without a `types` array, are skipped with a hint.
203
+ - `scripts/build.mjs`: CLI 2.4.0 replaces it when it is still an unmodified scaffold from an earlier CLI (line endings ignored; `src/main.js` / `src/main.ts` and `src/styles.css` / `src/styles.scss` still count). The interactive prompt defaults to yes. Without a TTY, and with `--yes`, the file is replaced. `--dry-run` writes nothing. An edited script is left unchanged and the CLI prints what `stagepass build`, `stagepass watch` and `stagepass dev` do now. A missing script stays missing. Published CLI 2.3.1 does not replace that file.
204
+ - `.htaccess`: since 2.4.1, when `stagepass.json` has `"php": true` and the project root has no `.htaccess`, upgrade writes the shipped template (same bytes as `stagepass new --php`). An existing file is not modified. If it has no `RewriteRule "(^|/)\." - [F]` line, a hint points at https://stagepass.one/docs/php/ and `api/README.md` and the command still exits 0. A symlink or directory at that name is left in place. Projects without `"php": true` are unchanged. `--dry-run` writes nothing. Published CLI 2.4.0 does not write this file.
170
205
 
171
206
  Every change is printed as `file: action` (unchanged files are not listed; skipped files appear as hints). `npm install` is printed, not run. Snippets use the major pin `@2` plus an optional exact pin note.
172
207
 
@@ -232,7 +267,7 @@ Stagepass reflects `Access-Control-Allow-Origin` for **allowed** browser `Origin
232
267
 
233
268
  Webflow staging/live hosts are **not** included by default. Add them per project, e.g. `--origin my-project.webflow.io`. An explicit `--origin *.webflow.io` (or `*.webflow.com`) is accepted but prints a warning (any Webflow user's site would then be allowed).
234
269
 
235
- Matching responses also send `Vary: Origin`. Preflight (`OPTIONS`) for allowed origins returns `204` with reflected ACAO, `Access-Control-Allow-Methods: GET, HEAD, POST, OPTIONS`, reflected `Access-Control-Allow-Headers`, `Access-Control-Max-Age: 86400`, and `Access-Control-Allow-Private-Network: true` (Chrome Private Network Access from public HTTPS → loopback).
270
+ Matching responses also send `Vary: Origin`. On HTTP 2xx, Caddy sets a single `Access-Control-Allow-Origin` with a deferred replace, so a PHP app that sends the same header does not produce a second value. Other status codes are not given an ACAO by Caddy. Preflight (`OPTIONS`) for allowed origins returns `204` with reflected ACAO, `Access-Control-Allow-Methods: GET, HEAD, POST, OPTIONS`, reflected `Access-Control-Allow-Headers`, `Access-Control-Max-Age: 86400`, and `Access-Control-Allow-Private-Network: true` (Chrome Private Network Access from public HTTPS → loopback).
236
271
 
237
272
  Non-matching origins get **no** ACAO. Non-allowlisted `OPTIONS` still get `204` without CORS headers.
238
273
 
@@ -267,6 +302,8 @@ On `stagepass link`, `reload`, and `start`, legacy Caddyfile blocks (no `# stage
267
302
  3. **`allowAllOrigins` is enabled** for migrated blocks so existing Webflow / live-domain embedding keeps working
268
303
  4. A short notice recommends tightening CORS
269
304
 
305
+ Blocks already marked `# stagepass-block: v2` are rewritten to the current marker on those same commands. Saved options (`allowAllOrigins`, origins, `php`, `devPort`) stay as they are.
306
+
270
307
  Recommended after migration:
271
308
 
272
309
  ```bash
@@ -276,6 +313,8 @@ stagepass link --no-allow-all-origins
276
313
 
277
314
  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).
278
315
 
316
+ The v3 block needs Caddy 2.9 or newer (`brew upgrade caddy`). Homebrew does not upgrade an existing Caddy when you `brew install caddy`. On a known older Caddy, `link`, `reload`, and `start` do not rewrite existing blocks. `link` still writes that project's block as v3 and warns that CORS on success responses may be missing until you upgrade. If `caddy version` cannot be read, the rewrite stays as before. `stagepass doctor` reports the version and warns below 2.9.
317
+
279
318
  ## Troubleshooting (CLI)
280
319
 
281
320
  | Symptom | What to check |
@@ -283,6 +322,7 @@ Hand-written content outside `# START:` / `# END:` markers is left untouched. Un
283
322
  | Autostart runs at login but `caddy: command not found` / daemon exits | Re-run `stagepass autostart on` so the plist embeds Homebrew `PATH`. Confirm `brew --prefix` and that `which caddy` points at `$prefix/bin/caddy` (Cellar symlink OK). |
284
323
  | 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. |
285
324
  | 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. |
325
+ | Login autostart points at a deleted Homebrew Node, or `doctor` warns that the daemon version differs from the CLI | Published CLI 2.3.1 and later. Run `stagepass autostart on`. `doctor` fails on a missing LaunchAgent node or CLI path, and warns on a versioned Cellar node path or a daemon/CLI version mismatch. The fix hint is `stagepass autostart on`. |
286
326
  | `stagepass start` spinner floods the terminal (weird ANSI) | Upgrade to a build with the spinner geometry guard. Rare with TTY width `0`. |
287
327
  | `start` asks for a password at every boot | There is no unconditional `sudo -v`. Only confirmed conflict resolution may use `sudo kill` / `apachectl`. |
288
328
  | 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`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "2.3.1",
3
+ "version": "2.4.1",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
package/src/cli.js CHANGED
@@ -62,6 +62,35 @@ export function rewriteArgvForUpgrade(argv) {
62
62
  return out;
63
63
  }
64
64
 
65
+ // Suggest subcommands for a top-level unknown option. Strip control chars. Do not run.
66
+ function suggestMisplacedOption(program, errorText) {
67
+ if (!errorText.startsWith("error: unknown option '")) return '';
68
+ const args = (program.args || []).map((s) => String(s).replace(/\p{C}/gu, ''));
69
+ const flag = args[0];
70
+ if (!flag || flag[0] !== '-' || flag === '--') return '';
71
+ const name = flag.split('=')[0];
72
+ const hits = [];
73
+ const walk = (cmd, prefix) => {
74
+ for (const sub of cmd.commands) {
75
+ const path = prefix.concat(sub.name());
76
+ if (sub.options.some((o) => o.long === name || o.short === name)) hits.push(path);
77
+ walk(sub, path);
78
+ }
79
+ };
80
+ walk(program, []);
81
+ if (!hits.length) return '';
82
+ const bin = program.name();
83
+ hits.sort((a, b) => (a.join(' ') < b.join(' ') ? -1 : a.join(' ') > b.join(' ') ? 1 : 0));
84
+ return hits
85
+ .map((cmdPath) => {
86
+ const rest = args.slice(1);
87
+ const echoed = cmdPath.every((part, i) => rest[i] === part);
88
+ const tail = echoed ? [flag, ...rest.slice(cmdPath.length)] : args;
89
+ return `Did you mean: ${bin} ${cmdPath.join(' ')} ${tail.join(' ')}\n`;
90
+ })
91
+ .join('');
92
+ }
93
+
65
94
  /**
66
95
  * Build the Commander program (no parse). Injectable handlers for unit tests.
67
96
  *
@@ -294,13 +323,13 @@ export function createProgram(deps = {}) {
294
323
  program
295
324
  .command('upgrade')
296
325
  .description(
297
- 'Bump @stagepass/*, sync modules, AGENTS.md, Cursor rule and types, print Webflow snippets'
326
+ 'Bump @stagepass/*, sync project files, replace an unmodified scripts/build.mjs, add a missing PHP .htaccess, print Webflow snippets'
298
327
  )
299
328
  .option('--dry-run', 'Show changes without writing any file')
300
329
  .option('--site <host>', 'Live Webflow site to detect loaded modules from (https)')
301
330
  .option('--site-modules <list>', 'Modules the site loads: none, all, or inject,cookies,maintenance')
302
331
  .option('--skip-site', 'Do not fetch the live site')
303
- .option('-y, --yes', 'Non-interactive; accept detected or existing modules')
332
+ .option('-y, --yes', 'Non-interactive; accept detected or existing modules and an unmodified scripts/build.mjs')
304
333
  .option(
305
334
  '--target <version>',
306
335
  'Target version, range or dist-tag; must be published on npm (default: ^<latest published 2.x>, ^2 offline)'
@@ -359,10 +388,10 @@ export function createProgram(deps = {}) {
359
388
  .option('--staging <domain>', 'Staging hostname written to stagepass.json as origin')
360
389
  .option('--production <domain>', 'Optional production hostname written to stagepass.json')
361
390
  .option('--site-modules <list>', 'Modules the site loads: none, all, or inject,cookies,maintenance')
362
- .option('--php', 'Enable PHP (api/ + php_fastcgi on link)')
391
+ .option('--php', 'Enable PHP (api/ boilerplate + php_fastcgi on link)')
363
392
  .option('--no-php', 'Disable PHP for this project (default)')
364
- .option('--php-examples', 'Include examples/php samples (requires --php)')
365
- .option('--no-php-examples', 'Skip PHP examples (default)')
393
+ .option('--php-examples', 'Deprecated: sample actions ship with --php under api/actions/')
394
+ .option('--no-php-examples', 'Deprecated no-op (examples are not a separate copy)')
366
395
  .option('--link', 'Run stagepass link after scaffolding (macOS)')
367
396
  .option('--no-link', 'Do not link after scaffolding (default)')
368
397
  .option('--git', 'Initialize a git repository')
@@ -378,5 +407,19 @@ export function createProgram(deps = {}) {
378
407
  process.exitCode = code;
379
408
  });
380
409
 
410
+ // Typo suggestions (commander). Root-only writer: subcommands already copied output config.
411
+ const enableSuggest = (cmd) => {
412
+ cmd.showSuggestionAfterError();
413
+ cmd.commands.forEach(enableSuggest);
414
+ };
415
+ enableSuggest(program);
416
+ program.configureOutput({
417
+ outputError(str, write) {
418
+ write(str);
419
+ const hint = suggestMisplacedOption(program, str);
420
+ if (hint) write(hint);
421
+ },
422
+ });
423
+
381
424
  return program;
382
425
  }
@@ -20,6 +20,8 @@ import { readStagepassJson } from '../lib/project-sync.js';
20
20
  import { getCaddyfilePath, getProjectsPath, validateRoot } from '../lib/paths.js';
21
21
  import { isPidAlive, isValidDevPort } from '../lib/dev-port.js';
22
22
  import { ensureStagepassReady } from '../lib/ensure-running.js';
23
+ import { warnPhpProject } from '../lib/php-runtime.js';
24
+ import { ensurePhpFpm } from '../lib/php-fpm.js';
23
25
  import { start as defaultStart } from './start.js';
24
26
 
25
27
  /** Grace before SIGKILL after a forwarded stop signal (overridable in tests). */
@@ -328,6 +330,18 @@ export async function dev(options = {}, deps = {}) {
328
330
 
329
331
  setupDone = true;
330
332
 
333
+ await warnPhpProject(cwd, {
334
+ fs: fse,
335
+ exec: deps.exec,
336
+ platform: deps.platform,
337
+ pathExists: deps.pathExists,
338
+ resolveCommand: deps.resolveCommand,
339
+ brewPrefix: deps.brewPrefix,
340
+ domain,
341
+ warn: (m) => log(chalk.yellow(m)),
342
+ ensurePhpFpm: deps.ensurePhpFpm || ensurePhpFpm,
343
+ });
344
+
331
345
  log(chalk.green(`Live reload on https://${domain}/__stagepass/live (127.0.0.1:${live.port})`));
332
346
  if (options.verbose) {
333
347
  log(chalk.dim('Running: npm run watch'));
@@ -17,6 +17,7 @@ import {
17
17
  isBroadWebflowWildcard,
18
18
  } from '../lib/origins.js';
19
19
  import { ensureCaddyfileMigrated } from '../lib/migrate.js';
20
+ import { CADDY_UPGRADE_HINT, readCaddyVersion } from '../lib/caddy-version.js';
20
21
  import {
21
22
  originsFromStagepassConfig,
22
23
  phpFromStagepassConfig,
@@ -36,6 +37,7 @@ import { isPhpEnabled } from '../lib/caddyfile.js';
36
37
  * @param {string} [deps.cwd]
37
38
  * @param {(msg?: string) => void} [deps.log]
38
39
  * @param {(msg?: string) => void} [deps.error]
40
+ * @param {import('../lib/exec.js').ExecFn} [deps.exec]
39
41
  */
40
42
  export async function link(domain, options = {}, deps = {}) {
41
43
  const log = deps.log || console.log;
@@ -127,7 +129,15 @@ export async function link(domain, options = {}, deps = {}) {
127
129
  await fs.ensureDir(caddyDir);
128
130
 
129
131
  spinner.stop();
130
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
132
+ const caddy = await readCaddyVersion(deps.exec);
133
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath, caddy });
134
+ if (caddy.known && !caddy.ok) {
135
+ log(
136
+ chalk.yellow(
137
+ ` This site block is v3 and needs Caddy 2.9 or newer for CORS on success responses. ${CADDY_UPGRADE_HINT}`
138
+ )
139
+ );
140
+ }
131
141
  await clearStaleDevPorts(projectsPath);
132
142
  spinner.start(`Linking ${chalk.bold(targetDomain)}...`);
133
143
 
@@ -33,6 +33,7 @@ import {
33
33
  import { updateConfigTypes } from '../lib/project-sync.js';
34
34
  import { validateOriginEntry, isBroadWebflowWildcard } from '../lib/origins.js';
35
35
  import { isMacOS } from '../lib/platform.js';
36
+ import { checkPhpRuntime, phpOriginsHint, phpProjectWarning } from '../lib/php-runtime.js';
36
37
  import { runDoctor } from '../lib/doctor.js';
37
38
  import { setup as defaultSetup } from './setup.js';
38
39
  import { link as defaultLink } from './link.js';
@@ -329,9 +330,6 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
329
330
  if (php === undefined) {
330
331
  php = await askYesNo(rl, 'Enable PHP for this project?', false);
331
332
  }
332
- if (php && phpExamples === undefined) {
333
- phpExamples = await askYesNo(rl, 'Include PHP examples under examples/php/?', false);
334
- }
335
333
  if (git === undefined) {
336
334
  git = await askYesNo(rl, 'Initialize git repository?', true);
337
335
  }
@@ -341,10 +339,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
341
339
  if (install === undefined) {
342
340
  install = await askYesNo(rl, 'Run npm install now?', false);
343
341
  }
344
- if (linkAtEnd === undefined) {
345
- // Asked after create on macOS only; remember preference here when already decided.
346
- linkAtEnd = undefined;
347
- }
342
+ // Asked after create on macOS only when the link flag was omitted.
348
343
  } finally {
349
344
  rl.close();
350
345
  }
@@ -389,7 +384,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
389
384
  if (install === undefined) install = false;
390
385
  if (php === undefined) php = false;
391
386
  if (phpExamples === undefined) phpExamples = false;
392
- if (linkAtEnd === undefined) linkAtEnd = false;
387
+ if (linkAtEnd == null && !interactive) linkAtEnd = false;
393
388
 
394
389
  if (lang !== 'ts' && lang !== 'js') {
395
390
  return { ok: false, error: 'Language must be ts or js.' };
@@ -397,11 +392,12 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
397
392
  if (styles !== 'scss' && styles !== 'css') {
398
393
  return { ok: false, error: 'Styles must be scss or css.' };
399
394
  }
400
- if (phpExamples && !php) {
401
- return {
402
- ok: false,
403
- error: '--php-examples requires PHP. Pass --php or omit --php-examples.',
404
- };
395
+ if (phpExamples) {
396
+ log(
397
+ chalk.yellow(
398
+ '--php-examples is deprecated. Sample actions (ping, contact) are included with --php under api/actions/. This flag no longer copies examples/php/.'
399
+ )
400
+ );
405
401
  }
406
402
 
407
403
  const remoteCheck = validateGitRemote(remote);
@@ -564,7 +560,7 @@ async function maybeDoctorPreflight(deps = {}) {
564
560
  }
565
561
 
566
562
  /**
567
- * Optionally link the new project (macOS only; interactive ask or --link).
563
+ * Optionally link the new project (macOS only; --link, or ask when unset).
568
564
  *
569
565
  * @param {object} config
570
566
  * @param {string} targetDir
@@ -580,9 +576,9 @@ async function maybeLinkProject(config, targetDir, deps = {}) {
580
576
  return;
581
577
  }
582
578
 
583
- let shouldLink = config.linkAtEnd === true;
579
+ let shouldLink = config.linkAtEnd;
584
580
  const isTty = deps.isTTY != null ? Boolean(deps.isTTY) : Boolean(input.isTTY);
585
- if (!shouldLink && isTty && deps.yes !== true) {
581
+ if (shouldLink == null && isTty && deps.yes !== true) {
586
582
  const rl =
587
583
  deps.createReadline?.() ||
588
584
  readline.createInterface({ input, output });
@@ -752,6 +748,7 @@ export async function createNew(nameArg, options = {}, deps = {}) {
752
748
  if (config.install) log(' (npm install)');
753
749
  if (config.linkAtEnd) log(' (stagepass link)');
754
750
  if (config.productionSkipped) log(` (${PRODUCTION_HINT})`);
751
+ await reportPhpChoice(config, deps, log);
755
752
  return 0;
756
753
  }
757
754
 
@@ -845,6 +842,7 @@ export async function createNew(nameArg, options = {}, deps = {}) {
845
842
  }
846
843
  log(chalk.dim(`Declared modules (stagepass.json): ${formatModules(config.siteModules)}`));
847
844
  log(chalk.dim(`PHP: ${config.php ? 'on' : 'off'}`));
845
+ await reportPhpChoice(config, deps, log);
848
846
 
849
847
  const snippets = buildWebflowSnippets({
850
848
  version: config.loaderVersion,
@@ -863,5 +861,30 @@ export async function createNew(nameArg, options = {}, deps = {}) {
863
861
  return 0;
864
862
  }
865
863
 
864
+ /**
865
+ * Origins hint plus a non-fatal PHP 8.2 / php-fpm check. The project is kept either way.
866
+ * @param {{ php?: boolean, name: string }} config
867
+ * @param {object} deps
868
+ * @param {(msg?: string) => void} log
869
+ */
870
+ async function reportPhpChoice(config, deps, log) {
871
+ if (config.php !== true) return;
872
+ log(chalk.dim(phpOriginsHint(config.name)));
873
+ try {
874
+ const runtime = await checkPhpRuntime({
875
+ exec: deps.exec,
876
+ platform: deps.platform,
877
+ pathExists: deps.pathExists,
878
+ resolveCommand: deps.resolveCommand,
879
+ brewPrefix: deps.brewPrefix,
880
+ });
881
+ if (!runtime.ok) {
882
+ log(chalk.yellow(phpProjectWarning(runtime, `${config.name}.sp`)));
883
+ }
884
+ } catch {
885
+ log(chalk.yellow('PHP could not be checked. The project was still created.'));
886
+ }
887
+ }
888
+
866
889
  /** Commander-facing alias */
867
890
  export const newProject = createNew;
@@ -3,6 +3,8 @@ import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import { defaultSpawn } from '../lib/spawn.js';
5
5
  import { ensureStagepassReady } from '../lib/ensure-running.js';
6
+ import { warnPhpProject } from '../lib/php-runtime.js';
7
+ import { ensurePhpFpm } from '../lib/php-fpm.js';
6
8
  import { start as defaultStart } from './start.js';
7
9
 
8
10
  /**
@@ -75,6 +77,18 @@ export async function runNpmScript(scriptName, options = {}, deps = {}) {
75
77
  * @returns {Promise<number>}
76
78
  */
77
79
  export async function watch(options = {}, deps = {}) {
80
+ const cwd = deps.cwd || process.cwd();
81
+ await warnPhpProject(cwd, {
82
+ fs: deps.fs,
83
+ exec: deps.exec,
84
+ platform: deps.platform,
85
+ pathExists: deps.pathExists,
86
+ resolveCommand: deps.resolveCommand,
87
+ brewPrefix: deps.brewPrefix,
88
+ domain: deps.domain,
89
+ warn: (m) => (deps.log || console.log)(chalk.yellow(m)),
90
+ ensurePhpFpm: deps.ensurePhpFpm || ensurePhpFpm,
91
+ });
78
92
  await (deps.ensureStagepassReady || ensureStagepassReady)(options, {
79
93
  ...deps,
80
94
  start: deps.start || defaultStart,
@@ -29,7 +29,11 @@ export async function reload(options = {}) {
29
29
 
30
30
  try {
31
31
  spinner.stop();
32
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFilePath, projectsPath });
32
+ await ensureCaddyfileMigrated({
33
+ caddyfilePath: caddyFilePath,
34
+ projectsPath,
35
+ exec: (file, args, opts) => execa(file, args, opts),
36
+ });
33
37
  await warnIfAllowAllOriginsActive({ caddyfilePath: caddyFilePath });
34
38
  spinner.start('Reloading Caddy...');
35
39
 
@@ -350,7 +350,7 @@ export async function start(options = {}) {
350
350
  // 3. Migrate legacy Caddyfile blocks before boot; drop dead live-reload ports
351
351
  await fs.ensureDir(caddyDir);
352
352
  if (await fs.pathExists(caddyFile)) {
353
- await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath });
353
+ await ensureCaddyfileMigrated({ caddyfilePath: caddyFile, projectsPath, exec });
354
354
  const stale = await clearStaleDevPorts(projectsPath);
355
355
  for (const domain of stale) {
356
356
  const project = await getProject(domain, projectsPath);