@stagepass/cli 2.4.0 → 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.
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.1 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.1: 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).
@@ -56,7 +56,7 @@ Linked: https://my-project.sp -> /absolute/path/to/project
56
56
  | `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
57
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. 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 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. |
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,8 +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. Published CLI 2.3.1 uses the Homebrew `bin/node` shim when the running node is a versioned Cellar path.
81
- - Published CLI 2.3.1 `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`.
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`.
82
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.
83
83
  - Manual macOS checklist: [`TESTING-macos.md`](./TESTING-macos.md).
84
84
 
@@ -95,7 +95,7 @@ These are different prompts. Grant only the narrow dialog macOS shows. Stagepass
95
95
  #### Install location and LaunchAgent paths
96
96
 
97
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.
98
- - `autostart on` records **absolute** Node and CLI paths plus the validated Homebrew `PATH`. Published CLI 2.3.1 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
+ - `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.
99
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.
100
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.
101
101
  - Development checkouts (`packages/cli`, Desktop test packs) and the published global install are different binaries; compare behaviour with one style at a time.
@@ -130,7 +130,35 @@ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `
130
130
 
131
131
  ### PHP
132
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` stays outside that folder. Copy `api/.env.example` to `.env` and set `ALLOWED_ORIGINS` (include `https://<name>.sp`). There is no mail. Caddy already returns 404 for hidden segments such as `/.env`, `/api/.env`, and `/.php/`. `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/` and `.php/config.php` into `dist/` and skips `.env`, `.php/rate-limit/`, logs, pid files, and key, certificate, or database files (`.pem`, `.key`, `.p12`, `.pfx`, `.crt`, `.cer`, `.sqlite`, `.db`). It keeps `.htaccess` and `.env.example`. `stagepass dev` / `watch` serve PHP from the project root, so edits show up on the next request. A longer draft for the website lives in [docs/php.md](https://github.com/arobertherz/stagepass/blob/master/docs/php.md); that page is not live yet.
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)).
134
162
 
135
163
  ### Declared modules (`stagepass.json`)
136
164
 
@@ -142,7 +170,7 @@ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `
142
170
 
143
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>`;
144
172
  - `.cursor/rules/stagepass.mdc` (globs `src/**`) with the same content;
145
- - `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.
146
174
 
147
175
  The legacy boolean `"modules": true|false` is still read; `upgrade` replaces it with a list (`true` becomes `["all"]` without a TTY).
148
176
 
@@ -173,6 +201,7 @@ Still not recognised: tags without `src`, `data-src` only, other hosts without a
173
201
  - `.cursor/rules/stagepass.mdc`: created if missing, otherwise only its managed block is refreshed.
174
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.
175
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.
176
205
 
177
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.
178
207
 
@@ -293,7 +322,7 @@ The v3 block needs Caddy 2.9 or newer (`brew upgrade caddy`). Homebrew does not
293
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). |
294
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. |
295
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. |
296
- | Login autostart points at a deleted Homebrew Node, or `doctor` warns that the daemon version differs from the CLI | Published CLI 2.3.1. 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`. |
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`. |
297
326
  | `stagepass start` spinner floods the terminal (weird ANSI) | Upgrade to a build with the spinner geometry guard. Rare with TTY width `0`. |
298
327
  | `start` asks for a password at every boot | There is no unconditional `sudo -v`. Only confirmed conflict resolution may use `sudo kill` / `apachectl`. |
299
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.4.0",
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
@@ -323,7 +323,7 @@ export function createProgram(deps = {}) {
323
323
  program
324
324
  .command('upgrade')
325
325
  .description(
326
- 'Bump @stagepass/*, sync project files, replace an unmodified scripts/build.mjs, print Webflow snippets'
326
+ 'Bump @stagepass/*, sync project files, replace an unmodified scripts/build.mjs, add a missing PHP .htaccess, print Webflow snippets'
327
327
  )
328
328
  .option('--dry-run', 'Show changes without writing any file')
329
329
  .option('--site <host>', 'Live Webflow site to detect loaded modules from (https)')
@@ -22,6 +22,7 @@ import {
22
22
  import { detectSite, normalizeSiteUrl } from '../lib/site-detect.js';
23
23
  import {
24
24
  applyProjectSync,
25
+ phpFromStagepassConfig,
25
26
  planProjectSync,
26
27
  readStagepassJson,
27
28
  resolveUpgradeModules,
@@ -30,6 +31,7 @@ import {
30
31
  defaultBuildScriptTemplatePath,
31
32
  planBuildScriptUpgrade,
32
33
  } from '../lib/build-script-upgrade.js';
34
+ import { planHtaccessUpgrade } from '../lib/htaccess-upgrade.js';
33
35
 
34
36
  const STAGEPASS_SCOPE = '@stagepass/';
35
37
 
@@ -171,7 +173,8 @@ export function applyStagepassVersions(pkg, target) {
171
173
  * Upgrade @stagepass/* deps in the current project's package.json and sync
172
174
  * the declared modules into stagepass.json, AGENTS.md, the Cursor rule and
173
175
  * tsconfig/jsconfig types. Replaces scripts/build.mjs when it is still an
174
- * unmodified scaffold from an earlier CLI.
176
+ * unmodified scaffold from an earlier CLI. When stagepass.json has `"php": true`
177
+ * and the project root has no `.htaccess`, writes the shipped template.
175
178
  *
176
179
  * @param {object} [options]
177
180
  * @param {boolean} [options.dryRun]
@@ -378,6 +381,22 @@ export async function upgrade(options = {}, deps = {}) {
378
381
  closeRl();
379
382
  }
380
383
 
384
+ // Missing PHP .htaccess only. An existing path is never replaced.
385
+ const htaccessPlan = await planHtaccessUpgrade({
386
+ cwd,
387
+ php: phpFromStagepassConfig(sp.data),
388
+ fse,
389
+ });
390
+ if (htaccessPlan.action === 'create') {
391
+ plan.writes.push({
392
+ file: '.htaccess',
393
+ content: htaccessPlan.content,
394
+ action: 'created',
395
+ });
396
+ } else if (htaccessPlan.note) {
397
+ plan.notes.push(htaccessPlan.note);
398
+ }
399
+
381
400
  log(chalk.bold(`\nProject files for modules: ${resolved.modules.length ? resolved.modules.join(', ') : 'none'}`));
382
401
  if (plan.writes.length === 0) {
383
402
  log(' Everything is up to date.');
@@ -29,7 +29,7 @@ export const BUILD_SCRIPT_CUSTOM_HINT = [
29
29
  `What the current scaffold does (${BUILD_SCRIPT_DOC_URL}):`,
30
30
  ' stagepass watch and stagepass dev write only stable dist/main.js and dist/styles.css. Hashed files and manifest.json stay as the last stagepass build left them.',
31
31
  ' stagepass build writes content hashes, stable copies, and SRI in dist/manifest.json, then deletes hashed files the previous manifest listed that this build does not. CLI 2.2.x manifests store those filenames as strings; those names are included. Only plain <base>.<8 hex><ext> files directly in dist/ are removed.',
32
- ' When stagepass.json has "php": true, stagepass build also copies api/ and .php/config.php into dist. It skips .env, .php/rate-limit, logs, pid files, and key, certificate, or database files (.pem, .key, .p12, .pfx, .crt, .cer, .sqlite, .db). It keeps .htaccess and .env.example. Watch does not copy them.',
32
+ ' When stagepass.json has "php": true, stagepass build also copies api/, .php/config.php, and a project-root .htaccess into dist. It skips .env, .php/.env, .php/rate-limit, 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 stays when the project has none. Watch does not copy them.',
33
33
  'Port that behavior into your script by hand. The Scripts section of a README from stagepass new describes the same stagepass build, stagepass watch and stagepass dev commands.',
34
34
  ].join('\n');
35
35
 
@@ -72,6 +72,11 @@ export const KNOWN_SCAFFOLD_BUILD_SCRIPTS = [
72
72
  commit: '983f090',
73
73
  sha256: '98578f87225fd03d08b7e5d5bbdecc07cbb6ccbbc754642c6e880bb2f53559bb',
74
74
  },
75
+ {
76
+ id: '2.4.0-keys',
77
+ commit: '6966954',
78
+ sha256: 'cba431ef9e0ff257ecced77613f6157c96d64f2a2db7679fcaa6467795d5ca9c',
79
+ },
75
80
  ];
76
81
 
77
82
  const TOKEN_SPECS = [
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Plan a missing PHP `.htaccess` for `stagepass upgrade`.
3
+ * Covered when the file contains the shipped line `RewriteRule "(^|/)\." - [F]`.
4
+ * Symlinks and directories are not followed and are not replaced.
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import fs from 'fs-extra';
10
+
11
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
+
13
+ /** Exact deny line from templates/project/htaccess. */
14
+ export const HTACCESS_DENY_LINE = 'RewriteRule "(^|/)\\." - [F]';
15
+
16
+ const HTACCESS_DOCS = 'https://stagepass.one/docs/php/ and api/README.md';
17
+
18
+ export function defaultHtaccessTemplatePath() {
19
+ return path.join(__dirname, '../../templates/project/htaccess');
20
+ }
21
+
22
+ export function htaccessHasDenyRule(source) {
23
+ return String(source).includes(HTACCESS_DENY_LINE);
24
+ }
25
+
26
+ /**
27
+ * Does not write. `php` must be the boolean from stagepass.json.
28
+ *
29
+ * @param {object} options
30
+ * @param {string} options.cwd
31
+ * @param {boolean} [options.php]
32
+ * @param {{ lstat: Function, readFile: Function }} [options.fse]
33
+ * @returns {Promise<{ action: 'skip' | 'create' | 'present' | 'hint' | 'blocked', content?: string, note?: string }>}
34
+ */
35
+ export async function planHtaccessUpgrade(options) {
36
+ if (options.php !== true) return { action: 'skip' };
37
+ const fse = options.fse || fs;
38
+ const abs = path.join(options.cwd, '.htaccess');
39
+ /** @type {import('node:fs').Stats} */
40
+ let st;
41
+ try {
42
+ st = await fse.lstat(abs);
43
+ } catch (err) {
44
+ if (err && /** @type {{ code?: string }} */ (err).code === 'ENOENT') {
45
+ try {
46
+ const content = await fse.readFile(defaultHtaccessTemplatePath(), 'utf8');
47
+ return { action: 'create', content };
48
+ } catch (readErr) {
49
+ const detail = readErr instanceof Error ? readErr.message : String(readErr);
50
+ return {
51
+ action: 'blocked',
52
+ note: `Could not read the .htaccess template (${detail}). Nothing was written.`,
53
+ };
54
+ }
55
+ }
56
+ return { action: 'blocked', note: '.htaccess could not be inspected; left unchanged.' };
57
+ }
58
+ if (st.isSymbolicLink()) {
59
+ return { action: 'blocked', note: '.htaccess is a symlink; left unchanged.' };
60
+ }
61
+ if (st.isDirectory()) {
62
+ return { action: 'blocked', note: '.htaccess is a directory; left unchanged.' };
63
+ }
64
+ if (!st.isFile()) {
65
+ return { action: 'blocked', note: '.htaccess is not a regular file; left unchanged.' };
66
+ }
67
+ /** @type {string} */
68
+ let raw;
69
+ try {
70
+ raw = await fse.readFile(abs, 'utf8');
71
+ } catch {
72
+ return { action: 'blocked', note: '.htaccess could not be read; left unchanged.' };
73
+ }
74
+ if (htaccessHasDenyRule(raw)) return { action: 'present' };
75
+ return {
76
+ action: 'hint',
77
+ note: `.htaccess exists and has no ${HTACCESS_DENY_LINE} line. Left unchanged. See ${HTACCESS_DOCS}.`,
78
+ };
79
+ }
@@ -70,6 +70,7 @@ export function scaffoldPhpTemplateMap(options = {}) {
70
70
  { template: 'api/lib/validate.php', out: 'api/lib/validate.php' },
71
71
  { template: 'api/env.example', out: 'api/.env.example' },
72
72
  { template: 'php-private/config.php', out: '.php/config.php' },
73
+ { template: 'htaccess', out: '.htaccess' },
73
74
  ];
74
75
  }
75
76
 
@@ -222,7 +223,8 @@ export async function planScaffoldFiles(options, deps = {}) {
222
223
  '## PHP',
223
224
  '',
224
225
  `PHP is on. Caddy serves \`https://${options.name}.sp/api/action.php\` with \`php_fastcgi\`.`,
225
- 'Read `api/README.md`. Copy `api/.env.example` to `.env` (do not commit it) and set `ALLOWED_ORIGINS` to exact origins, including that `.sp` URL.',
226
+ 'Read `api/README.md`. Copy `api/.env.example` to `.env` in the project root (do not commit it) and set `ALLOWED_ORIGINS` to exact origins, including that `.sp` URL. From Webflow, call the PHP host with its absolute URL, not `window.location.origin`.',
227
+ 'Apache uses the project `.htaccess`. nginx needs the snippet in `api/README.md` before the PHP location.',
226
228
  '',
227
229
  ].join('\n')
228
230
  : [
@@ -4,7 +4,7 @@ Plain PHP 8.2 or newer. No framework. No Composer. No mail.
4
4
 
5
5
  `api/action.php` is the only public entry. Every request names an `action`. That name is looked up in `api/actions.php` and then handed to a file in `api/actions/`. User input is never used as a file path or a function name.
6
6
 
7
- A longer guide is planned at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/). That page is not live yet.
7
+ A longer guide is at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/). Copy `api/.env.example` to `.env` in the project root, or use `.php/.env`. `stagepass build` never copies `.env` into `dist`.
8
8
 
9
9
  ## Where to edit
10
10
 
@@ -33,8 +33,9 @@ api/actions/ping.php GET health check
33
33
  api/actions/contact.php POST form handler (validates only, does not send mail)
34
34
  api/lib/ Shared helpers (core)
35
35
  api/.env.example Copy to the project root as .env
36
- .php/config.php Config outside the public api/ folder
37
- .php/rate-limit/ Created at runtime, not public
36
+ .php/config.php Optional overrides, inside the document root (the folder that contains api/)
37
+ .php/rate-limit/ Runtime files, not copied to dist. Deny hidden paths on the host
38
+ .htaccess Apache deny for hidden paths (shipped)
38
39
  .env Local environment (do not commit)
39
40
  ```
40
41
 
@@ -42,7 +43,16 @@ api/.env.example Copy to the project root as .env
42
43
 
43
44
  1. Copy `api/.env.example` to `.env` in the project root (the folder that contains `api/`).
44
45
  2. Set `ALLOWED_ORIGINS` to the exact site origins that may call this API, including the scheme and without a trailing slash. Typical values are `https://your-project.sp`, `https://your-site.webflow.io`, and `https://www.example.com`.
45
- 3. Keep `.env` out of git. On Stagepass, Caddy already returns 404 for hidden path segments such as `.env` and `.php`. On shared hosting, the document root is the folder that contains `api/` (the uploaded `dist/` contents), so the public URL stays `/api/action.php`. Deny hidden paths such as `/.env` and `/.php/` in the host config when you can.
46
+ 3. Keep `.env` out of git. The document root is the folder that contains `api/` (the project root locally, `dist/` after `stagepass build`). Caddy returns 404 for any path segment that starts with `.`. Since 2.4.1 this starter ships a web-root `.htaccess` (Apache needs `AllowOverride All` and `mod_rewrite`). `stagepass upgrade` writes that file when `stagepass.json` has `"php": true` and the project root has none. An existing `.htaccess` is left unchanged. If it has no `RewriteRule "(^|/)\." - [F]` line, add that rule yourself. Published CLI 2.4.0 does not write the file. `stagepass build` copies the project `.htaccess` into `dist/` and does not replace an existing project `.htaccess`. It does not copy `.env`, `.php/.env`, or `.php/rate-limit/`. nginx does not read `.htaccess`. Put this in the server block before `location ~ \.php$`:
47
+
48
+ ```nginx
49
+ location ~* /\.(?!well-known\/) {
50
+ deny all;
51
+ }
52
+ ```
53
+
54
+ Prefer real environment variables on the host so a `.env` file is not required in the web root.
55
+ 4. `stagepass build` copies `api/` to `dist/api/`, `.php/config.php` to `dist/.php/config.php`, and the project `.htaccess` to `dist/.htaccess`. Upload `dist/`. The public URL stays `/api/action.php`.
46
56
 
47
57
  `APP_ENV=local` turns on a hidden `boom` action used only to test error handling. Leave `APP_ENV=production` on a live host.
48
58
 
@@ -87,13 +97,13 @@ return static function (array $input, array $config): array {
87
97
 
88
98
  ## Call it from JavaScript
89
99
 
90
- Use the existing Stagepass loader helpers. When a local session is active, `sp.resolveLocalUrl` points at `https://your-project.sp/...`. Otherwise use the public URL of the same path on your host.
100
+ `sp.resolveLocalUrl` returns a local HTTPS URL only during an active `.sp` session, otherwise `''`. On a Webflow page `window.location.origin` is the Webflow host, and Webflow does not run PHP. There is no helper for the public PHP base URL (`origin` and `production` in `stagepass.json` are Webflow hosts). Use the absolute URL of the PHP host, for example `https://php.example.com/api/action.php`.
91
101
 
92
102
  ```js
93
103
  const path = '/api/action.php';
94
- const url =
95
- (sp.vars.isLocal && sp.resolveLocalUrl(path)) ||
96
- new URL(path, window.location.origin).href;
104
+ const phpHost = 'https://php.example.com';
105
+ const local = sp.vars.isLocal && sp.resolveLocalUrl(path);
106
+ const url = local || phpHost + path;
97
107
 
98
108
  const response = await fetch(url, {
99
109
  method: 'POST',
@@ -124,13 +134,35 @@ A simple GET check:
124
134
  ```js
125
135
  const url =
126
136
  (sp.vars.isLocal && sp.resolveLocalUrl('/api/action.php')) ||
127
- '/api/action.php';
137
+ 'https://php.example.com/api/action.php';
128
138
 
129
139
  const result = await fetch(url + '?action=ping', {
130
140
  headers: { Accept: 'application/json' },
131
141
  }).then((r) => r.json());
132
142
  ```
133
143
 
144
+ `contact.php` validates a JSON or form POST and does not send mail. A native Webflow form needs its own submit listener. There is no shipped helper for that.
145
+
146
+ ```js
147
+ form.addEventListener('submit', async (event) => {
148
+ event.preventDefault();
149
+ const url =
150
+ (sp.vars.isLocal && sp.resolveLocalUrl('/api/action.php')) ||
151
+ 'https://php.example.com/api/action.php';
152
+ await fetch(url, {
153
+ method: 'POST',
154
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
155
+ body: JSON.stringify({
156
+ action: 'contact',
157
+ name: form.elements.name.value,
158
+ email: form.elements.email.value,
159
+ message: form.elements.message.value,
160
+ website: '',
161
+ }),
162
+ });
163
+ });
164
+ ```
165
+
134
166
  ## Response shape
135
167
 
136
168
  Every response is JSON with `status`, `data`, and `message`, plus a matching HTTP status code.
@@ -159,7 +191,7 @@ Every response is JSON with `status`, `data`, and `message`, plus a matching HTT
159
191
 
160
192
  ## Security defaults
161
193
 
162
- POST actions require an `Origin` header that is on `ALLOWED_ORIGINS`. GET `ping` may omit `Origin`, but a present `Origin` still has to match the list. CORS headers are only sent for allowed origins. A filled honeypot field (`website` by default) returns a generic success and does not run the handler. Rate limiting is per IP and action, stored as files under `.php/rate-limit/`.
194
+ POST actions require an `Origin` header that is on `ALLOWED_ORIGINS`. GET `ping` may omit `Origin`, but a present `Origin` still has to match the list. CORS headers are only sent for allowed origins. A filled honeypot field (`website` by default) returns a generic success and does not run the handler. Rate limiting is per IP and action, stored as files under `.php/rate-limit/`. `rate_limit_allows()` is fail-open: if the directory cannot be created, the file cannot be opened, `flock` fails, or the limiter throws, the request is allowed. Directory and file failures, and thrown errors, are logged. A failed `flock` allows the request and does not write its own log line. `client_ip()` uses only `REMOTE_ADDR`, never `X-Forwarded-For`. Do not trust that header without a proxy allowlist. Behind a reverse proxy or CDN every visitor can share one address, so the limit applies to everyone together. This stays fail-open.
163
195
 
164
196
  ## Local PHP server
165
197
 
@@ -171,4 +203,6 @@ php -S 127.0.0.1:8080 -t .
171
203
 
172
204
  Then: `curl 'http://127.0.0.1:8080/api/action.php?action=ping'`
173
205
 
206
+ `php -S 127.0.0.1:8080 -t api` serves `/action.php` and does not match this layout. PHP's built-in server does not return 404 for hidden paths the way Caddy does (`/.env`, `/.php/`). Do not point `php -S -t .` at a folder that already contains a real `.env`. Prefer `stagepass dev` or the linked `.sp` domain.
207
+
174
208
  On a linked Stagepass domain the same file is reached at `https://your-project.sp/api/action.php`.
@@ -40,6 +40,9 @@ if ($method === 'OPTIONS') {
40
40
  if ($origin === '' || !origin_is_allowed($origin, $allowedOrigins)) {
41
41
  respond_fail(['origin' => 'Origin is not allowed.'], 'Origin is not allowed.', 403);
42
42
  }
43
+ if (!headers_sent()) {
44
+ header_remove('X-Powered-By');
45
+ }
43
46
  http_response_code(204);
44
47
  header('Content-Length: 0');
45
48
  exit;
@@ -22,9 +22,8 @@ function project_root(): string
22
22
  }
23
23
 
24
24
  /**
25
- * Hidden directory for config and rate-limit files.
26
- *
27
- * On Stagepass, Caddy already returns 404 for any path segment starting with ".".
25
+ * Config and rate-limit directory, inside the document root (the folder that contains api/).
26
+ * Deny hidden paths with the shipped .htaccess, the nginx snippet in api/README.md, or Caddy locally.
28
27
  */
29
28
  function private_dir(): string
30
29
  {
@@ -130,7 +129,7 @@ function env_list(string $key): array
130
129
  }
131
130
 
132
131
  /**
133
- * Load configuration from .env and an optional PHP config file outside the public root.
132
+ * Load configuration from the project-root .env, .php/.env, and optional .php/config.php.
134
133
  *
135
134
  * @return array{
136
135
  * env: string,
@@ -0,0 +1,7 @@
1
+ <IfModule mod_rewrite.c>
2
+ RewriteEngine On
3
+ RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
4
+ RewriteCond %{SCRIPT_FILENAME} -d [OR]
5
+ RewriteCond %{SCRIPT_FILENAME} -f
6
+ RewriteRule "(^|/)\." - [F]
7
+ </IfModule>
@@ -1,9 +1,9 @@
1
1
  <?php
2
2
 
3
3
  /**
4
- * Optional PHP config, kept outside the public api/ directory.
5
- * Edit values here or in .env. Values in this file override the .env defaults.
6
- * On Stagepass, Caddy already returns 404 for hidden path segments such as ".php".
4
+ * Optional PHP config. The document root is the folder that contains api/, so this file is inside it.
5
+ * load_config() reads .env in the project root and .php/.env. Values here override those defaults.
6
+ * Hidden paths: shipped .htaccess on Apache, the nginx snippet in api/README.md, Caddy 404 locally.
7
7
  */
8
8
 
9
9
  declare(strict_types=1);
@@ -213,7 +213,20 @@ async function copyFiltered(src, dest) {
213
213
  }
214
214
  }
215
215
 
216
- /** PHP projects: upload bundle is dist/api plus dist/.php/config.php. Watch serves the project root. */
216
+ /** Copy a regular project-root .htaccess. Missing source leaves dist/.htaccess alone. */
217
+ async function publishRootHtaccess() {
218
+ const src = path.join(root, '.htaccess');
219
+ let st;
220
+ try {
221
+ st = await fs.lstat(src);
222
+ } catch {
223
+ return;
224
+ }
225
+ if (!st.isFile()) return;
226
+ await fs.copyFile(src, path.join(distDir, '.htaccess'));
227
+ }
228
+
229
+ /** PHP projects: dist/api, dist/.php/config.php, and dist/.htaccess. Watch serves the project root. */
217
230
  async function publishPhp() {
218
231
  if (watchMode) return;
219
232
  let cfg;
@@ -224,6 +237,7 @@ async function publishPhp() {
224
237
  }
225
238
  if (!cfg || cfg.php !== true) return;
226
239
  await copyFiltered(path.join(root, 'api'), path.join(distDir, 'api'));
240
+ await publishRootHtaccess();
227
241
  const configSrc = path.join(root, '.php', 'config.php');
228
242
  let st;
229
243
  try {