@stagepass/cli 2.3.0 → 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.
- package/README.md +35 -24
- package/package.json +1 -1
- package/src/cli.js +48 -5
- package/src/commands/daemon.js +18 -2
- package/src/commands/dev.js +14 -0
- package/src/commands/link.js +11 -1
- package/src/commands/new.js +39 -16
- package/src/commands/npm-run.js +14 -0
- package/src/commands/reload.js +5 -1
- package/src/commands/start.js +1 -1
- package/src/commands/upgrade.js +84 -32
- package/src/lib/autostart.js +66 -8
- package/src/lib/build-script-upgrade.js +244 -0
- package/src/lib/caddy-version.js +31 -0
- package/src/lib/caddyfile.js +76 -36
- package/src/lib/doctor-site.js +15 -10
- package/src/lib/doctor.js +131 -30
- package/src/lib/migrate.js +29 -2
- package/src/lib/package-versions.js +1 -1
- package/src/lib/paths.js +5 -0
- package/src/lib/php-runtime.js +249 -0
- package/src/lib/scaffold.js +22 -16
- package/templates/project/README.md.tmpl +8 -6
- package/templates/project/api/README.md.tmpl +172 -5
- package/templates/project/api/action.php +100 -0
- package/templates/project/api/actions/boom.php +21 -0
- package/templates/project/api/actions/contact.php +46 -0
- package/templates/project/api/actions/ping.php +23 -0
- package/templates/project/api/actions.php +59 -0
- package/templates/project/api/env.example +25 -0
- package/templates/project/api/lib/bootstrap.php +44 -0
- package/templates/project/api/lib/config.php +180 -0
- package/templates/project/api/lib/request.php +94 -0
- package/templates/project/api/lib/response.php +97 -0
- package/templates/project/api/lib/security.php +114 -0
- package/templates/project/api/lib/validate.php +69 -0
- package/templates/project/gitignore +4 -0
- package/templates/project/php-private/config.php +24 -0
- package/templates/project/scripts/build.mjs +114 -8
- package/templates/project/examples/php/README.md.tmpl +0 -18
- package/templates/project/examples/php/form.php +0 -105
- package/templates/project/examples/php/proxy.php +0 -171
|
@@ -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
|
+
}
|
package/src/lib/scaffold.js
CHANGED
|
@@ -47,22 +47,30 @@ export function scaffoldTemplateMap(lang, styles) {
|
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
/**
|
|
50
|
-
*
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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]
|
|
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
|
-
|
|
217
|
-
|
|
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
|
-
|
|
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
|
-
| `
|
|
20
|
-
| `
|
|
21
|
-
| `
|
|
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
|
|
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
|
-
`
|
|
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
|
-
#
|
|
1
|
+
# Stagepass PHP boilerplate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Plain PHP 8.2 or newer. No framework. No Composer. No mail.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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`.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Single public entry for Stagepass PHP actions.
|
|
5
|
+
* Core file: leave this alone unless you are changing how routing works.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* GET /api/action.php?action=ping
|
|
9
|
+
* POST /api/action.php with JSON { "action": "contact", "name": "...", ... }
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
declare(strict_types=1);
|
|
13
|
+
|
|
14
|
+
define('STAGEPASS_PHP_ENTRY', true);
|
|
15
|
+
|
|
16
|
+
// Core library, then the allowlist you edit in actions.php.
|
|
17
|
+
require __DIR__ . '/lib/bootstrap.php';
|
|
18
|
+
require __DIR__ . '/actions.php';
|
|
19
|
+
|
|
20
|
+
install_error_handlers();
|
|
21
|
+
|
|
22
|
+
ini_set('display_errors', '0');
|
|
23
|
+
ini_set('display_startup_errors', '0');
|
|
24
|
+
|
|
25
|
+
$config = load_config();
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
date_default_timezone_set((string) $config['timezone']);
|
|
29
|
+
} catch (Throwable $e) {
|
|
30
|
+
date_default_timezone_set('UTC');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
$origin = request_origin();
|
|
34
|
+
$allowedOrigins = $config['allowed_origins'];
|
|
35
|
+
$method = request_method();
|
|
36
|
+
|
|
37
|
+
apply_cors_headers($origin, $allowedOrigins);
|
|
38
|
+
|
|
39
|
+
if ($method === 'OPTIONS') {
|
|
40
|
+
if ($origin === '' || !origin_is_allowed($origin, $allowedOrigins)) {
|
|
41
|
+
respond_fail(['origin' => 'Origin is not allowed.'], 'Origin is not allowed.', 403);
|
|
42
|
+
}
|
|
43
|
+
http_response_code(204);
|
|
44
|
+
header('Content-Length: 0');
|
|
45
|
+
exit;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
$input = parse_input((int) $config['max_body_bytes']);
|
|
49
|
+
|
|
50
|
+
$action = input_string($input, 'action');
|
|
51
|
+
$catalog = action_catalog($config);
|
|
52
|
+
|
|
53
|
+
if ($action === '' || !isset($catalog[$action])) {
|
|
54
|
+
respond_fail(['action' => 'Unknown action.'], 'Unknown action.', 404);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
$spec = $catalog[$action];
|
|
58
|
+
$allowedMethods = $spec['methods'];
|
|
59
|
+
|
|
60
|
+
if (!in_array($method, $allowedMethods, true)) {
|
|
61
|
+
if (!headers_sent()) {
|
|
62
|
+
header('Allow: ' . implode(', ', $allowedMethods));
|
|
63
|
+
}
|
|
64
|
+
respond_fail(
|
|
65
|
+
['method' => 'Use ' . implode(' or ', $allowedMethods) . '.'],
|
|
66
|
+
'Method not allowed.',
|
|
67
|
+
405
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
$originRequired = $spec['origin'] === 'required';
|
|
72
|
+
if ($originRequired && $origin === '') {
|
|
73
|
+
respond_fail(['origin' => 'Origin header is required.'], 'Origin is not allowed.', 403);
|
|
74
|
+
}
|
|
75
|
+
if ($origin !== '' && !origin_is_allowed($origin, $allowedOrigins)) {
|
|
76
|
+
respond_fail(['origin' => 'Origin is not allowed.'], 'Origin is not allowed.', 403);
|
|
77
|
+
}
|
|
78
|
+
if ($allowedOrigins === [] && $originRequired) {
|
|
79
|
+
respond_fail(['origin' => 'No origins are configured.'], 'Origin is not allowed.', 403);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if ($spec['rate_limit'] && !rate_limit_allows(client_ip(), $action, (int) $config['rate_limit_max'], (int) $config['rate_limit_window'])) {
|
|
83
|
+
if (!headers_sent()) {
|
|
84
|
+
header('Retry-After: ' . (string) $config['rate_limit_window']);
|
|
85
|
+
}
|
|
86
|
+
respond_fail(['rate_limit' => 'Too many requests. Try again later.'], 'Too many requests.', 429);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if ($spec['honeypot']) {
|
|
90
|
+
$honeypot = (string) $config['honeypot_field'];
|
|
91
|
+
if (honeypot_is_filled($input, $honeypot)) {
|
|
92
|
+
// Look like a normal success so bots do not learn the field name.
|
|
93
|
+
respond_success(['received' => true]);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
$handler = load_handler($spec['file']);
|
|
98
|
+
$data = $handler($input, $config);
|
|
99
|
+
|
|
100
|
+
respond_success(is_array($data) ? $data : ['ok' => true]);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Local-only hook to confirm unexpected exceptions become a generic HTTP 500.
|
|
5
|
+
* It is not registered unless APP_ENV is "local". Leave this as a test hook.
|
|
6
|
+
*
|
|
7
|
+
* @return callable(array<string, mixed>, array): array<string, mixed>
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
declare(strict_types=1);
|
|
11
|
+
|
|
12
|
+
if (!defined('STAGEPASS_PHP_ENTRY')) {
|
|
13
|
+
http_response_code(404);
|
|
14
|
+
header('Content-Type: application/json; charset=utf-8');
|
|
15
|
+
echo '{"status":"fail","data":null,"message":"Not found."}';
|
|
16
|
+
exit;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return static function (array $input, array $config): array {
|
|
20
|
+
throw new RuntimeException('SECRET_INTERNAL_TRACE should never reach the client.');
|
|
21
|
+
};
|