@stagepass/cli 2.3.1 → 2.4.0

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 (39) hide show
  1. package/README.md +24 -13
  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 +84 -32
  11. package/src/lib/build-script-upgrade.js +244 -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/migrate.js +29 -2
  17. package/src/lib/package-versions.js +1 -1
  18. package/src/lib/php-runtime.js +249 -0
  19. package/src/lib/scaffold.js +22 -16
  20. package/templates/project/README.md.tmpl +8 -6
  21. package/templates/project/api/README.md.tmpl +172 -5
  22. package/templates/project/api/action.php +100 -0
  23. package/templates/project/api/actions/boom.php +21 -0
  24. package/templates/project/api/actions/contact.php +46 -0
  25. package/templates/project/api/actions/ping.php +23 -0
  26. package/templates/project/api/actions.php +59 -0
  27. package/templates/project/api/env.example +25 -0
  28. package/templates/project/api/lib/bootstrap.php +44 -0
  29. package/templates/project/api/lib/config.php +180 -0
  30. package/templates/project/api/lib/request.php +94 -0
  31. package/templates/project/api/lib/response.php +97 -0
  32. package/templates/project/api/lib/security.php +114 -0
  33. package/templates/project/api/lib/validate.php +69 -0
  34. package/templates/project/gitignore +4 -0
  35. package/templates/project/php-private/config.php +24 -0
  36. package/templates/project/scripts/build.mjs +114 -8
  37. package/templates/project/examples/php/README.md.tmpl +0 -18
  38. package/templates/project/examples/php/form.php +0 -105
  39. package/templates/project/examples/php/proxy.php +0 -171
@@ -2,10 +2,12 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import {
5
+ BLOCK_VERSION,
5
6
  formatBackupStamp,
6
7
  migrateLegacyContent,
7
8
  parseBlocks,
8
9
  } from './caddyfile.js';
10
+ import { CADDY_UPGRADE_HINT, readCaddyVersion } from './caddy-version.js';
9
11
  import { ensureMigratedProject } from './projects.js';
10
12
  import { getCaddyfilePath, getProjectsPath } from './paths.js';
11
13
 
@@ -17,6 +19,8 @@ import { getCaddyfilePath, getProjectsPath } from './paths.js';
17
19
  * @param {string} [options.caddyfilePath]
18
20
  * @param {string} [options.projectsPath]
19
21
  * @param {boolean} [options.silent]
22
+ * @param {import('./exec.js').ExecFn} [options.exec]
23
+ * @param {Awaited<ReturnType<typeof readCaddyVersion>>} [options.caddy]
20
24
  * @returns {Promise<{ changed: boolean, migrated: Array, skipped: Array, backupPath: string|null }>}
21
25
  */
22
26
  export async function ensureCaddyfileMigrated(options = {}) {
@@ -25,10 +29,24 @@ export async function ensureCaddyfileMigrated(options = {}) {
25
29
  const silent = options.silent === true;
26
30
 
27
31
  if (!(await fs.pathExists(caddyfilePath))) {
28
- return { changed: false, migrated: [], skipped: [], backupPath: null };
32
+ return { changed: false, migrated: [], upgraded: [], skipped: [], backupPath: null };
29
33
  }
30
34
 
31
35
  const original = await fs.readFile(caddyfilePath, 'utf-8');
36
+ const caddy = options.caddy || (await readCaddyVersion(options.exec));
37
+ const current = new RegExp(`# stagepass-block:\\s*${BLOCK_VERSION}\\b`);
38
+ const stale = parseBlocks(original).some((block) => !current.test(block.full));
39
+ if (caddy.known && !caddy.ok && stale) {
40
+ if (!silent) {
41
+ console.log(
42
+ chalk.yellow(
43
+ ` Caddy ${caddy.version} is older than 2.9, so existing site blocks were left unchanged. ${CADDY_UPGRADE_HINT}`
44
+ )
45
+ );
46
+ }
47
+ return { changed: false, migrated: [], upgraded: [], skipped: [], backupPath: null };
48
+ }
49
+
32
50
  const result = migrateLegacyContent(original, {
33
51
  warn: silent
34
52
  ? () => {}
@@ -39,6 +57,7 @@ export async function ensureCaddyfileMigrated(options = {}) {
39
57
  return {
40
58
  changed: false,
41
59
  migrated: [],
60
+ upgraded: [],
42
61
  skipped: result.skipped,
43
62
  backupPath: null,
44
63
  };
@@ -52,7 +71,7 @@ export async function ensureCaddyfileMigrated(options = {}) {
52
71
  await ensureMigratedProject(item.domain, item.root, projectsPath);
53
72
  }
54
73
 
55
- if (!silent) {
74
+ if (!silent && result.migrated.length > 0) {
56
75
  console.log(
57
76
  chalk.yellow(
58
77
  ` Migrated ${result.migrated.length} legacy Caddy block(s). Backup: ${path.basename(backupPath)}`
@@ -67,10 +86,18 @@ export async function ensureCaddyfileMigrated(options = {}) {
67
86
  )
68
87
  );
69
88
  }
89
+ if (!silent && result.upgraded.length > 0) {
90
+ console.log(
91
+ chalk.dim(
92
+ ` Updated ${result.upgraded.length} Caddy block(s) to stagepass-block ${BLOCK_VERSION}.`
93
+ )
94
+ );
95
+ }
70
96
 
71
97
  return {
72
98
  changed: true,
73
99
  migrated: result.migrated,
100
+ upgraded: result.upgraded,
74
101
  skipped: result.skipped,
75
102
  backupPath,
76
103
  };
@@ -5,5 +5,5 @@
5
5
  * Sourced from packages/loader and packages/modules package.json at generate time.
6
6
  * The published CLI ships this snapshot; it cannot read the monorepo at runtime.
7
7
  */
8
- export const LOADER_VERSION = "2.4.0";
8
+ export const LOADER_VERSION = "2.5.0";
9
9
  export const MODULES_VERSION = "2.2.2";
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Shared PHP 8.2+ / php-fpm (or php-cgi) check for new, doctor, dev, and watch.
3
+ * `exec` is injectable. Never throws on a missing binary.
4
+ */
5
+
6
+ import fs from 'fs-extra';
7
+ import path from 'node:path';
8
+ import { defaultExec, resolveCommand } from './exec.js';
9
+ import { phpFromStagepassConfig, readStagepassJson } from './project-sync.js';
10
+ import { ensurePhpFpm as defaultEnsurePhpFpm } from './php-fpm.js';
11
+
12
+ /** Drop C0/DEL and collapse whitespace so command output cannot break a line. */
13
+ export function plainLine(value, max = 240) {
14
+ const text = String(value ?? '')
15
+ .replace(/[\u0000-\u001F\u007F]/g, ' ')
16
+ .replace(/\s+/g, ' ')
17
+ .trim();
18
+ return text.length > max ? text.slice(0, max) : text;
19
+ }
20
+
21
+ /**
22
+ * @param {string} text
23
+ * @returns {{ major: number, minor: number, patch: number, label: string } | null}
24
+ */
25
+ export function parsePhpVersion(text) {
26
+ const match = plainLine(text).match(/PHP\s+(\d+)\.(\d+)\.(\d+)/);
27
+ if (!match) return null;
28
+ return {
29
+ major: Number(match[1]),
30
+ minor: Number(match[2]),
31
+ patch: Number(match[3]),
32
+ label: `${match[1]}.${match[2]}.${match[3]}`,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * @param {{ major: number, minor: number } | null} version
38
+ */
39
+ export function phpVersionOk(version) {
40
+ if (!version) return false;
41
+ if (version.major > 8) return true;
42
+ if (version.major < 8) return false;
43
+ return version.minor >= 2;
44
+ }
45
+
46
+ /**
47
+ * @param {string} [platform]
48
+ */
49
+ export function phpInstallHint(platform) {
50
+ if (platform === 'darwin') {
51
+ return 'Install on macOS: brew install php\nThen start it: brew services start php';
52
+ }
53
+ return 'Install PHP 8.2 or newer and php-fpm (or php-cgi). On Debian/Ubuntu: sudo apt install php-fpm, then start the php-fpm service.';
54
+ }
55
+
56
+ /**
57
+ * @param {import('./exec.js').ExecFn} exec
58
+ * @param {string} file
59
+ * @param {string[]} args
60
+ */
61
+ async function capture(exec, file, args) {
62
+ try {
63
+ const result = await exec(file, args);
64
+ return {
65
+ stdout: result && result.stdout != null ? String(result.stdout) : '',
66
+ stderr: result && result.stderr != null ? String(result.stderr) : '',
67
+ };
68
+ } catch (err) {
69
+ const error = /** @type {{ stdout?: string, stderr?: string }} */ (err);
70
+ return {
71
+ stdout: error && error.stdout != null ? String(error.stdout) : '',
72
+ stderr: error && error.stderr != null ? String(error.stderr) : '',
73
+ };
74
+ }
75
+ }
76
+
77
+ /**
78
+ * @param {object} [opts]
79
+ * @param {import('./exec.js').ExecFn} [opts.exec]
80
+ * @param {typeof resolveCommand} [opts.resolveCommand]
81
+ * @param {(p: string) => Promise<boolean>} [opts.pathExists]
82
+ * @param {string|null} [opts.brewPrefix]
83
+ * @param {string} [opts.platform]
84
+ * @returns {Promise<{
85
+ * ok: boolean,
86
+ * status: 'ok'|'warn'|'fail',
87
+ * message: string,
88
+ * detail: string,
89
+ * version: { major: number, minor: number, patch: number, label: string } | null,
90
+ * phpPath: string|null,
91
+ * fastcgi: string|null,
92
+ * }>}
93
+ */
94
+ export async function checkPhpRuntime(opts = {}) {
95
+ const exec = opts.exec || defaultExec;
96
+ const which = opts.resolveCommand || resolveCommand;
97
+ const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
98
+ const platform = opts.platform || process.platform;
99
+ const hint = phpInstallHint(platform);
100
+
101
+ const phpPath = await which('php', exec);
102
+ let fpm = await which('php-fpm', exec);
103
+ const cgi = await which('php-cgi', exec);
104
+ if (!fpm && opts.brewPrefix) {
105
+ const candidate = path.join(opts.brewPrefix, 'sbin', 'php-fpm');
106
+ if (await pathExists(candidate)) fpm = candidate;
107
+ }
108
+ const fastcgi = fpm || cgi || null;
109
+ const fastcgiLabel = fpm ? 'php-fpm' : 'php-cgi';
110
+
111
+ /** @type {{ major: number, minor: number, patch: number, label: string } | null} */
112
+ let version = null;
113
+ if (phpPath) {
114
+ const out = await capture(exec, phpPath, ['-v']);
115
+ version = parsePhpVersion(`${out.stdout}\n${out.stderr}`);
116
+ }
117
+
118
+ const base = { version, phpPath, fastcgi };
119
+
120
+ if (!phpPath && !fastcgi) {
121
+ return {
122
+ ...base,
123
+ ok: false,
124
+ status: 'fail',
125
+ message: 'PHP / php-fpm not found',
126
+ detail: hint,
127
+ };
128
+ }
129
+ if (phpPath && !version) {
130
+ return {
131
+ ...base,
132
+ ok: false,
133
+ status: 'warn',
134
+ message: `PHP found (${plainLine(phpPath)}) but the version could not be read (need 8.2 or newer)`,
135
+ detail: hint,
136
+ };
137
+ }
138
+ if (version && !phpVersionOk(version)) {
139
+ return {
140
+ ...base,
141
+ ok: false,
142
+ status: 'warn',
143
+ message: `PHP ${version.label} is older than 8.2`,
144
+ detail: hint,
145
+ };
146
+ }
147
+ if (!fastcgi) {
148
+ return {
149
+ ...base,
150
+ ok: false,
151
+ status: 'warn',
152
+ message: `PHP ${version ? version.label : 'found'} (${plainLine(phpPath)}) but neither php-fpm nor php-cgi was found`,
153
+ detail: `Caddy php_fastcgi uses 127.0.0.1:9000. ${hint}`,
154
+ };
155
+ }
156
+ if (!phpPath || !version) {
157
+ return {
158
+ ...base,
159
+ ok: false,
160
+ status: 'warn',
161
+ message: `${fastcgiLabel} found (${plainLine(fastcgi)}) but the php CLI was not found, so the version was not checked (need 8.2 or newer)`,
162
+ detail: hint,
163
+ };
164
+ }
165
+ return {
166
+ ...base,
167
+ ok: true,
168
+ status: 'ok',
169
+ message: `PHP ${version.label} and ${fastcgiLabel} found (${plainLine(fastcgi)}; php=${plainLine(phpPath)})`,
170
+ detail: '',
171
+ };
172
+ }
173
+
174
+ /**
175
+ * @param {string} name validated project name
176
+ */
177
+ export function phpOriginsHint(name) {
178
+ const safe = plainLine(name).replace(/[^a-z0-9-]/gi, '') || 'your-project';
179
+ return `Copy api/.env.example to .env in the project root (do not commit .env). Set ALLOWED_ORIGINS to exact origins with no trailing slash, including https://${safe}.sp`;
180
+ }
181
+
182
+ /**
183
+ * Warning for new / dev / watch. Does not include a stack trace.
184
+ * @param {{ message: string, detail?: string }} result
185
+ * @param {string} [domain] linked name.sp
186
+ */
187
+ export function phpProjectWarning(result, domain) {
188
+ const host = plainLine(domain).replace(/[^a-z0-9.-]/gi, '') || '<project>.sp';
189
+ const lines = [result.message];
190
+ if (result.detail) lines.push(result.detail);
191
+ lines.push(
192
+ `JavaScript build and live reload will continue. https://${host}/api/action.php needs PHP before it can answer.`
193
+ );
194
+ return lines.join('\n');
195
+ }
196
+
197
+ /**
198
+ * Warn when this project opted into PHP and the runtime is missing or too old.
199
+ * Does not throw and does not stop the JS build.
200
+ *
201
+ * @param {string} cwd
202
+ * @param {object} [opts]
203
+ * @param {typeof fs} [opts.fs]
204
+ * @param {import('./exec.js').ExecFn} [opts.exec]
205
+ * @param {(msg: string) => void} [opts.warn]
206
+ * @param {string} [opts.domain]
207
+ * @param {boolean} [opts.ensure] start php-fpm when the runtime looks usable
208
+ */
209
+ export async function warnPhpProject(cwd, opts = {}) {
210
+ const fse = opts.fs || fs;
211
+ const warn = opts.warn || (() => {});
212
+ let data = null;
213
+ try {
214
+ const sp = await readStagepassJson(cwd, fse);
215
+ data = sp.data;
216
+ } catch {
217
+ return { applicable: false };
218
+ }
219
+ if (phpFromStagepassConfig(data) !== true) return { applicable: false };
220
+
221
+ let result;
222
+ try {
223
+ result = await checkPhpRuntime(opts);
224
+ } catch {
225
+ warn('PHP could not be checked. JavaScript build and live reload will continue.');
226
+ return { applicable: true, ok: false };
227
+ }
228
+ if (!result.ok) {
229
+ warn(phpProjectWarning(result, opts.domain));
230
+ return { applicable: true, ok: false, result };
231
+ }
232
+ if (opts.ensure !== false) {
233
+ const ensure = opts.ensurePhpFpm || defaultEnsurePhpFpm;
234
+ try {
235
+ const started = await ensure({ exec: opts.exec, stdio: 'ignore' });
236
+ if (!started || started.ok === false) {
237
+ const detail = plainLine(started && started.detail);
238
+ warn(
239
+ detail
240
+ ? `PHP-FPM was not started (${detail}). JavaScript build and live reload will continue.`
241
+ : 'PHP-FPM was not started. JavaScript build and live reload will continue.'
242
+ );
243
+ }
244
+ } catch {
245
+ warn('PHP-FPM was not started. JavaScript build and live reload will continue.');
246
+ }
247
+ }
248
+ return { applicable: true, ok: true, result };
249
+ }
@@ -47,22 +47,30 @@ export function scaffoldTemplateMap(lang, styles) {
47
47
  }
48
48
 
49
49
  /**
50
- * Extra files when PHP is enabled for the project.
50
+ * Boilerplate files when PHP is enabled.
51
+ * Dot paths are renamed in the package (npm pack drops dotfiles) and restored on write.
52
+ * `phpExamples` is ignored: sample actions live in api/actions/.
51
53
  * @param {{ php?: boolean, phpExamples?: boolean }} options
52
54
  * @returns {{ template: string, out: string }[]}
53
55
  */
54
56
  export function scaffoldPhpTemplateMap(options = {}) {
55
57
  if (options.php !== true) return [];
56
- /** @type {{ template: string, out: string }[]} */
57
- const files = [{ template: 'api/README.md.tmpl', out: 'api/README.md' }];
58
- if (options.phpExamples === true) {
59
- files.push(
60
- { template: 'examples/php/form.php', out: 'examples/php/form.php' },
61
- { template: 'examples/php/proxy.php', out: 'examples/php/proxy.php' },
62
- { template: 'examples/php/README.md.tmpl', out: 'examples/php/README.md' }
63
- );
64
- }
65
- return files;
58
+ return [
59
+ { template: 'api/README.md.tmpl', out: 'api/README.md' },
60
+ { template: 'api/action.php', out: 'api/action.php' },
61
+ { template: 'api/actions.php', out: 'api/actions.php' },
62
+ { template: 'api/actions/ping.php', out: 'api/actions/ping.php' },
63
+ { template: 'api/actions/contact.php', out: 'api/actions/contact.php' },
64
+ { template: 'api/actions/boom.php', out: 'api/actions/boom.php' },
65
+ { template: 'api/lib/bootstrap.php', out: 'api/lib/bootstrap.php' },
66
+ { template: 'api/lib/config.php', out: 'api/lib/config.php' },
67
+ { template: 'api/lib/request.php', out: 'api/lib/request.php' },
68
+ { template: 'api/lib/response.php', out: 'api/lib/response.php' },
69
+ { template: 'api/lib/security.php', out: 'api/lib/security.php' },
70
+ { template: 'api/lib/validate.php', out: 'api/lib/validate.php' },
71
+ { template: 'api/env.example', out: 'api/.env.example' },
72
+ { template: 'php-private/config.php', out: '.php/config.php' },
73
+ ];
66
74
  }
67
75
 
68
76
  /**
@@ -77,7 +85,7 @@ export function scaffoldPhpTemplateMap(options = {}) {
77
85
  * @property {string} [origin] Staging / primary live host (stagepass.json `origin`)
78
86
  * @property {string} [production] Optional production host (stagepass.json `production`)
79
87
  * @property {boolean} [php] Enable PHP FastCGI for the linked .sp site (default false for new)
80
- * @property {boolean} [phpExamples] Include examples/php samples (requires php)
88
+ * @property {boolean} [phpExamples] Deprecated. Accepted and ignored; actions ship in api/actions/.
81
89
  * @property {boolean} git
82
90
  * @property {string} [remote]
83
91
  * @property {boolean} install
@@ -213,10 +221,8 @@ export async function planScaffoldFiles(options, deps = {}) {
213
221
  ? [
214
222
  '## PHP',
215
223
  '',
216
- 'This project enables PHP for the linked `.sp` site (`php_fastcgi`). Put handlers under `api/`.',
217
- options.phpExamples
218
- ? 'Optional samples live in `examples/php/` (copy or adapt; do not expose secrets).'
219
- : 'Optional samples: re-run scaffolding with `--php --php-examples`, or copy from the Stagepass docs.',
224
+ `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.',
220
226
  '',
221
227
  ].join('\n')
222
228
  : [
@@ -6,7 +6,7 @@ Local Stagepass project for Webflow.
6
6
 
7
7
  ```bash
8
8
  npm install
9
- npm run build
9
+ stagepass build
10
10
  stagepass link {{NAME}}
11
11
  ```
12
12
 
@@ -16,9 +16,11 @@ stagepass link {{NAME}}
16
16
 
17
17
  | Script | Description |
18
18
  | :--- | :--- |
19
- | `npm run build` | Bundle JS/CSS into `dist/` with content hashes, SRI, and `manifest.json` |
20
- | `npm run watch` | Rebuild on change |
21
- | `npm run dev` | Alias of `watch` (until a real HMR server ships) |
19
+ | `stagepass build` | Production bundle: content hashes, SRI, and `dist/manifest.json` |
20
+ | `stagepass watch` | Rebuild stable `dist/main.js` and `dist/styles.css` only |
21
+ | `stagepass dev` | Watch plus live reload |
22
+
23
+ Hashes and `manifest.json` come only from `stagepass build`. `stagepass watch` and `stagepass dev` write only the stable files and leave the manifest as the last production build. `stagepass upgrade` replaces `scripts/build.mjs` when it is still an unmodified scaffold from an older CLI. A script you have edited is left in place; the CLI prints what `stagepass build`, `stagepass watch` and `stagepass dev` do now.
22
24
 
23
25
  ## Webflow Custom Code
24
26
 
@@ -38,11 +40,11 @@ Optional exact pin (replace `@2` in the URL if you need a locked version): `@{{L
38
40
  {{FOOTER_SNIPPET}}
39
41
  ```
40
42
 
41
- After each production upload, set `data-src` / `data-href` to your hosted URLs. For content-hashed uploads, read `file` from `dist/manifest.json`. Local Stagepass swapping can keep using the stable `dist/main.js` and `dist/styles.css` copies.
43
+ After each production upload, set `data-src` / `data-href` to your hosted URLs. For content-hashed uploads, read `file` from `dist/manifest.json` (last `stagepass build`). Local swapping uses the stable `dist/main.js` and `dist/styles.css` copies.
42
44
 
43
45
  ### Subresource Integrity (SRI)
44
46
 
45
- `npm run build` writes a sha384 `integrity` per output in `dist/manifest.json`:
47
+ `stagepass build` writes a sha384 `integrity` per output in `dist/manifest.json`:
46
48
 
47
49
  ```json
48
50
  {
@@ -1,7 +1,174 @@
1
- # API (PHP)
1
+ # Stagepass PHP boilerplate
2
2
 
3
- This folder is the project document root for PHP handlers served by Caddy `php_fastcgi` on your linked `.sp` domain.
3
+ Plain PHP 8.2 or newer. No framework. No Composer. No mail.
4
4
 
5
- - Put scripts here (for example `api/contact.php` → `https://{{NAME}}.sp/api/contact.php`).
6
- - Do not commit secrets. Load credentials from environment variables.
7
- - Prefer JSON responses and escape any HTML you render (`htmlspecialchars`).
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
+
7
+ A longer guide is planned at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/). That page is not live yet.
8
+
9
+ ## Where to edit
10
+
11
+ Edit these:
12
+
13
+ ```
14
+ api/actions.php Allowlist: register a new action here
15
+ api/actions/*.php Your action logic (see contact.php)
16
+ .env Origins, limits, APP_ENV (copy from api/.env.example)
17
+ .php/config.php Optional PHP overrides of the .env defaults
18
+ ```
19
+
20
+ Leave these alone unless you are changing the core:
21
+
22
+ ```
23
+ api/action.php Front controller
24
+ api/lib/* Responses, request parsing, security, validation, config
25
+ ```
26
+
27
+ ## Layout
28
+
29
+ ```
30
+ api/action.php Public front controller (core)
31
+ api/actions.php Action allowlist (you edit this)
32
+ api/actions/ping.php GET health check
33
+ api/actions/contact.php POST form handler (validates only, does not send mail)
34
+ api/lib/ Shared helpers (core)
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
38
+ .env Local environment (do not commit)
39
+ ```
40
+
41
+ ## Configure
42
+
43
+ 1. Copy `api/.env.example` to `.env` in the project root (the folder that contains `api/`).
44
+ 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
+
47
+ `APP_ENV=local` turns on a hidden `boom` action used only to test error handling. Leave `APP_ENV=production` on a live host.
48
+
49
+ ## Add a new action
50
+
51
+ 1. Create `api/actions/newsletter.php`. The file must return a callable. Read fields with `input_string()`. Throw `ValidationException` when input is invalid (that is a 422 fail). Any other uncaught exception becomes a generic 500 error.
52
+
53
+ ```php
54
+ <?php
55
+ declare(strict_types=1);
56
+
57
+ if (!defined('STAGEPASS_PHP_ENTRY')) {
58
+ http_response_code(404);
59
+ exit;
60
+ }
61
+
62
+ return static function (array $input, array $config): array {
63
+ $errors = [];
64
+ validate_required($input, 'email', $errors);
65
+ validate_email($input, 'email', $errors);
66
+ if ($errors !== []) {
67
+ throw new ValidationException($errors);
68
+ }
69
+ // Your logic here.
70
+ return ['subscribed' => true];
71
+ };
72
+ ```
73
+
74
+ 2. Register the name in `api/actions.php`:
75
+
76
+ ```php
77
+ 'newsletter' => [
78
+ 'file' => 'newsletter.php',
79
+ 'methods' => ['POST'],
80
+ 'honeypot' => true,
81
+ 'rate_limit' => true,
82
+ 'origin' => 'required',
83
+ ],
84
+ ```
85
+
86
+ 3. Call it from JavaScript with `action: 'newsletter'`. Do not add a second public PHP file unless you have a strong reason.
87
+
88
+ ## Call it from JavaScript
89
+
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.
91
+
92
+ ```js
93
+ const path = '/api/action.php';
94
+ const url =
95
+ (sp.vars.isLocal && sp.resolveLocalUrl(path)) ||
96
+ new URL(path, window.location.origin).href;
97
+
98
+ const response = await fetch(url, {
99
+ method: 'POST',
100
+ headers: {
101
+ Accept: 'application/json',
102
+ 'Content-Type': 'application/json',
103
+ },
104
+ body: JSON.stringify({
105
+ action: 'contact',
106
+ name: 'Ada Lovelace',
107
+ email: 'ada@example.com',
108
+ message: 'Hello',
109
+ website: '', // honeypot; leave empty, hide this field in CSS
110
+ }),
111
+ });
112
+
113
+ const result = await response.json();
114
+ // result.status is "success", "fail", or "error"
115
+ if (result.status === 'success') {
116
+ console.log('Saved', result.data);
117
+ } else {
118
+ console.warn(result.message, result.data);
119
+ }
120
+ ```
121
+
122
+ A simple GET check:
123
+
124
+ ```js
125
+ const url =
126
+ (sp.vars.isLocal && sp.resolveLocalUrl('/api/action.php')) ||
127
+ '/api/action.php';
128
+
129
+ const result = await fetch(url + '?action=ping', {
130
+ headers: { Accept: 'application/json' },
131
+ }).then((r) => r.json());
132
+ ```
133
+
134
+ ## Response shape
135
+
136
+ Every response is JSON with `status`, `data`, and `message`, plus a matching HTTP status code.
137
+
138
+ ```json
139
+ { "status": "success", "data": { "pong": true }, "message": null }
140
+ ```
141
+
142
+ ```json
143
+ {
144
+ "status": "fail",
145
+ "data": { "email": "A valid email is required." },
146
+ "message": "Validation failed."
147
+ }
148
+ ```
149
+
150
+ ```json
151
+ {
152
+ "status": "error",
153
+ "data": null,
154
+ "message": "An unexpected error occurred. Try again later."
155
+ }
156
+ ```
157
+
158
+ `fail` is a rejected request (validation 422, unknown action 404, wrong method 405, disallowed origin 403, too many requests 429). `error` is an unexpected server failure (500) and never includes internal details.
159
+
160
+ ## Security defaults
161
+
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/`.
163
+
164
+ ## Local PHP server
165
+
166
+ From the project root (the folder that contains `api/`):
167
+
168
+ ```bash
169
+ php -S 127.0.0.1:8080 -t .
170
+ ```
171
+
172
+ Then: `curl 'http://127.0.0.1:8080/api/action.php?action=ping'`
173
+
174
+ On a linked Stagepass domain the same file is reached at `https://your-project.sp/api/action.php`.