@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.
- package/README.md +24 -13
- package/package.json +1 -1
- package/src/cli.js +48 -5
- 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/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 +30 -29
- package/src/lib/migrate.js +29 -2
- package/src/lib/package-versions.js +1 -1
- 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,114 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Origin allowlist, CORS, honeypot, and the file-based rate limiter.
|
|
5
|
+
* Core file: you rarely need to edit this.
|
|
6
|
+
* Change origins, limits, and the honeypot field name in .env.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
declare(strict_types=1);
|
|
10
|
+
|
|
11
|
+
if (!defined('STAGEPASS_PHP_ENTRY')) {
|
|
12
|
+
http_response_code(404);
|
|
13
|
+
header('Content-Type: application/json; charset=utf-8');
|
|
14
|
+
echo '{"status":"fail","data":null,"message":"Not found."}';
|
|
15
|
+
exit;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function origin_is_allowed(string $origin, array $allowed): bool
|
|
19
|
+
{
|
|
20
|
+
if ($origin === '' || $allowed === []) {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
return in_array($origin, $allowed, true);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Send CORS headers when the Origin is on the allowlist. Never echo an unknown origin.
|
|
28
|
+
*/
|
|
29
|
+
function apply_cors_headers(string $origin, array $allowed): void
|
|
30
|
+
{
|
|
31
|
+
if (!origin_is_allowed($origin, $allowed)) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (headers_sent()) {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
header('Access-Control-Allow-Origin: ' . $origin);
|
|
38
|
+
header('Vary: Origin');
|
|
39
|
+
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
|
|
40
|
+
header('Access-Control-Allow-Headers: Content-Type, Accept');
|
|
41
|
+
header('Access-Control-Max-Age: 86400');
|
|
42
|
+
header('Access-Control-Allow-Credentials: false');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function honeypot_is_filled(array $input, string $field): bool
|
|
46
|
+
{
|
|
47
|
+
return $field !== '' && input_string($input, $field) !== '';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* File-based fixed-window limiter, keyed by IP and action.
|
|
52
|
+
*
|
|
53
|
+
* @return bool True when the request may proceed.
|
|
54
|
+
*/
|
|
55
|
+
function rate_limit_allows(string $ip, string $action, int $max, int $window): bool
|
|
56
|
+
{
|
|
57
|
+
if ($max <= 0 || $window <= 0) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
$dir = private_dir() . '/rate-limit';
|
|
62
|
+
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
|
|
63
|
+
error_log('stagepass-php: could not create the rate-limit directory.');
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
$file = $dir . '/' . hash('sha256', $ip . '|' . $action) . '.json';
|
|
68
|
+
$handle = fopen($file, 'c+');
|
|
69
|
+
if ($handle === false) {
|
|
70
|
+
error_log('stagepass-php: could not open a rate-limit file.');
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
if (!flock($handle, LOCK_EX)) {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
$raw = stream_get_contents($handle);
|
|
79
|
+
$decoded = [];
|
|
80
|
+
if (is_string($raw) && $raw !== '') {
|
|
81
|
+
$parsed = json_decode($raw, true);
|
|
82
|
+
if (is_array($parsed)) {
|
|
83
|
+
$decoded = $parsed;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
$now = time();
|
|
88
|
+
$cutoff = $now - $window;
|
|
89
|
+
$hits = [];
|
|
90
|
+
foreach ($decoded as $ts) {
|
|
91
|
+
if (is_numeric($ts) && (int) $ts > $cutoff) {
|
|
92
|
+
$hits[] = (int) $ts;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (count($hits) >= $max) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
$hits[] = $now;
|
|
101
|
+
rewind($handle);
|
|
102
|
+
ftruncate($handle, 0);
|
|
103
|
+
fwrite($handle, json_encode($hits, JSON_THROW_ON_ERROR));
|
|
104
|
+
fflush($handle);
|
|
105
|
+
|
|
106
|
+
return true;
|
|
107
|
+
} catch (Throwable $e) {
|
|
108
|
+
error_log('stagepass-php: rate-limit error: ' . $e->getMessage());
|
|
109
|
+
return true;
|
|
110
|
+
} finally {
|
|
111
|
+
flock($handle, LOCK_UN);
|
|
112
|
+
fclose($handle);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Field checks used by your actions.
|
|
5
|
+
* Throw ValidationException when input is invalid. That becomes a 422 fail.
|
|
6
|
+
* Add a helper here only when several actions share the same check.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
declare(strict_types=1);
|
|
10
|
+
|
|
11
|
+
if (!defined('STAGEPASS_PHP_ENTRY')) {
|
|
12
|
+
http_response_code(404);
|
|
13
|
+
header('Content-Type: application/json; charset=utf-8');
|
|
14
|
+
echo '{"status":"fail","data":null,"message":"Not found."}';
|
|
15
|
+
exit;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Validation failure with per-field messages (JSend "fail", HTTP 422).
|
|
20
|
+
*/
|
|
21
|
+
final class ValidationException extends RuntimeException
|
|
22
|
+
{
|
|
23
|
+
/** @param array<string, string> $errors */
|
|
24
|
+
public function __construct(private array $errors)
|
|
25
|
+
{
|
|
26
|
+
parent::__construct('Validation failed.');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @return array<string, string> */
|
|
30
|
+
public function errors(): array
|
|
31
|
+
{
|
|
32
|
+
return $this->errors;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function validate_required(array $input, string $key, array &$errors): void
|
|
37
|
+
{
|
|
38
|
+
if (input_string($input, $key) === '') {
|
|
39
|
+
$errors[$key] = 'This field is required.';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validate_email(array $input, string $key, array &$errors): void
|
|
44
|
+
{
|
|
45
|
+
if (isset($errors[$key])) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
$value = input_string($input, $key);
|
|
49
|
+
if ($value === '') {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
|
|
53
|
+
$errors[$key] = 'A valid email is required.';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function validate_max_length(array $input, string $key, int $max, array &$errors): void
|
|
58
|
+
{
|
|
59
|
+
if (isset($errors[$key])) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
$value = input_string($input, $key);
|
|
63
|
+
if ($value === '') {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (strlen($value) > $max) {
|
|
67
|
+
$errors[$key] = 'This field is too long (maximum ' . $max . ' characters).';
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
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".
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
declare(strict_types=1);
|
|
10
|
+
|
|
11
|
+
if (!defined('STAGEPASS_PHP_ENTRY')) {
|
|
12
|
+
http_response_code(404);
|
|
13
|
+
exit;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return [
|
|
17
|
+
'env' => env_string('APP_ENV', 'production'),
|
|
18
|
+
'allowed_origins' => env_list('ALLOWED_ORIGINS'),
|
|
19
|
+
'honeypot_field' => env_string('HONEYPOT_FIELD', 'website'),
|
|
20
|
+
'rate_limit_max' => env_int('RATE_LIMIT_MAX', 20),
|
|
21
|
+
'rate_limit_window' => env_int('RATE_LIMIT_WINDOW', 60),
|
|
22
|
+
'max_body_bytes' => env_int('MAX_BODY_BYTES', 65536),
|
|
23
|
+
'timezone' => env_string('APP_TIMEZONE', 'Europe/Berlin'),
|
|
24
|
+
];
|
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* Stagepass project build: esbuild (+ optional sass)
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* and writes a dist file only when its bytes changed.
|
|
3
|
+
* Stagepass project build: esbuild (+ optional sass).
|
|
4
|
+
* Production: hashed files, stable copies, manifest.json (sha384 SRI), then drop stale hashes.
|
|
5
|
+
* Older manifests store a filename string (CLI 2.2.x) or `{ file, integrity }`.
|
|
6
|
+
* `--watch`: stable dist/main.js and dist/styles.css only. Does not touch manifest.json.
|
|
7
|
+
* Writes a dist file only when its bytes changed. Watch rebuilds the affected part.
|
|
9
8
|
*/
|
|
10
9
|
import { createHash } from 'node:crypto';
|
|
11
10
|
import { watch as fsWatch, promises as fs } from 'node:fs';
|
|
@@ -66,12 +65,13 @@ async function writeHashed(stableName, contents, encoding = undefined) {
|
|
|
66
65
|
const buf = Buffer.isBuffer(contents)
|
|
67
66
|
? contents
|
|
68
67
|
: Buffer.from(contents, encoding || 'utf8');
|
|
68
|
+
await writeIfChanged(path.join(distDir, stableName), buf);
|
|
69
|
+
if (watchMode) return { file: stableName };
|
|
69
70
|
const hash = hashContent(buf);
|
|
70
71
|
const ext = path.extname(stableName);
|
|
71
72
|
const base = path.basename(stableName, ext);
|
|
72
73
|
const hashedName = `${base}.${hash}${ext}`;
|
|
73
74
|
await writeIfChanged(path.join(distDir, hashedName), buf);
|
|
74
|
-
await writeIfChanged(path.join(distDir, stableName), buf);
|
|
75
75
|
return {
|
|
76
76
|
file: hashedName,
|
|
77
77
|
integrity: sriSha384(buf),
|
|
@@ -79,7 +79,7 @@ async function writeHashed(stableName, contents, encoding = undefined) {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
async function writeManifest() {
|
|
82
|
-
if (!manifestState['main.js'] || !manifestState['styles.css']) return;
|
|
82
|
+
if (watchMode || !manifestState['main.js'] || !manifestState['styles.css']) return;
|
|
83
83
|
const text = `${JSON.stringify(
|
|
84
84
|
{
|
|
85
85
|
'main.js': manifestState['main.js'],
|
|
@@ -134,10 +134,116 @@ async function buildCss() {
|
|
|
134
134
|
return manifestState['styles.css'];
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
function safeHashName(name) {
|
|
138
|
+
return typeof name === 'string'
|
|
139
|
+
&& name === path.basename(name)
|
|
140
|
+
&& !name.includes('..')
|
|
141
|
+
&& !name.includes('\\')
|
|
142
|
+
&& !path.isAbsolute(name)
|
|
143
|
+
&& /^[\w-]+\.[0-9a-f]{8}\.[A-Za-z0-9]+$/.test(name);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Filename recorded for one manifest entry.
|
|
148
|
+
* CLI 2.2.x stored a string. Later scaffolds store `{ file, integrity }`.
|
|
149
|
+
* @param {unknown} entry
|
|
150
|
+
* @returns {string}
|
|
151
|
+
*/
|
|
152
|
+
function manifestEntryName(entry) {
|
|
153
|
+
if (typeof entry === 'string') return entry;
|
|
154
|
+
if (entry && typeof entry === 'object' && !Array.isArray(entry) && typeof entry.file === 'string') {
|
|
155
|
+
return entry.file;
|
|
156
|
+
}
|
|
157
|
+
return '';
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function priorHashNames() {
|
|
161
|
+
try {
|
|
162
|
+
const data = JSON.parse(await fs.readFile(path.join(distDir, 'manifest.json'), 'utf8'));
|
|
163
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return [];
|
|
164
|
+
const names = [];
|
|
165
|
+
for (const entry of Object.values(data)) {
|
|
166
|
+
const name = manifestEntryName(entry);
|
|
167
|
+
if (name) names.push(name);
|
|
168
|
+
}
|
|
169
|
+
return names;
|
|
170
|
+
} catch {
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function removeStaleHashes(prev) {
|
|
176
|
+
const keep = new Set(['main.js', 'styles.css'].map((k) => manifestState[k] && manifestState[k].file));
|
|
177
|
+
for (const name of prev) {
|
|
178
|
+
if (keep.has(name) || !safeHashName(name)) continue;
|
|
179
|
+
try {
|
|
180
|
+
const file = path.join(distDir, name);
|
|
181
|
+
if (!(await fs.lstat(file)).isFile()) continue;
|
|
182
|
+
await fs.unlink(file);
|
|
183
|
+
} catch {
|
|
184
|
+
/* missing */
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function skipPublishName(name) {
|
|
190
|
+
if (name === '.env' || (name.startsWith('.env') && name !== '.env.example')) return true;
|
|
191
|
+
return (
|
|
192
|
+
name === 'rate-limit' ||
|
|
193
|
+
name.endsWith('.log') ||
|
|
194
|
+
name.endsWith('.pid') ||
|
|
195
|
+
/\.(pem|key|p12|pfx|crt|cer|sqlite|db)$/i.test(name)
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function copyFiltered(src, dest) {
|
|
200
|
+
let entries;
|
|
201
|
+
try {
|
|
202
|
+
entries = await fs.readdir(src, { withFileTypes: true });
|
|
203
|
+
} catch {
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
await fs.mkdir(dest, { recursive: true });
|
|
207
|
+
for (const ent of entries) {
|
|
208
|
+
if (skipPublishName(ent.name) || ent.isSymbolicLink()) continue;
|
|
209
|
+
const from = path.join(src, ent.name);
|
|
210
|
+
const to = path.join(dest, ent.name);
|
|
211
|
+
if (ent.isDirectory()) await copyFiltered(from, to);
|
|
212
|
+
else if (ent.isFile()) await fs.copyFile(from, to);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** PHP projects: upload bundle is dist/api plus dist/.php/config.php. Watch serves the project root. */
|
|
217
|
+
async function publishPhp() {
|
|
218
|
+
if (watchMode) return;
|
|
219
|
+
let cfg;
|
|
220
|
+
try {
|
|
221
|
+
cfg = JSON.parse(await fs.readFile(path.join(root, 'stagepass.json'), 'utf8'));
|
|
222
|
+
} catch {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (!cfg || cfg.php !== true) return;
|
|
226
|
+
await copyFiltered(path.join(root, 'api'), path.join(distDir, 'api'));
|
|
227
|
+
const configSrc = path.join(root, '.php', 'config.php');
|
|
228
|
+
let st;
|
|
229
|
+
try {
|
|
230
|
+
st = await fs.lstat(configSrc);
|
|
231
|
+
} catch {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (!st.isFile()) return;
|
|
235
|
+
const destDir = path.join(distDir, '.php');
|
|
236
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
237
|
+
await fs.copyFile(configSrc, path.join(destDir, 'config.php'));
|
|
238
|
+
}
|
|
239
|
+
|
|
137
240
|
async function buildOnce() {
|
|
138
241
|
await ensureDist();
|
|
242
|
+
const prev = watchMode ? null : await priorHashNames();
|
|
139
243
|
await buildJsOnce();
|
|
140
244
|
await buildCss();
|
|
245
|
+
if (prev) await removeStaleHashes(prev);
|
|
246
|
+
await publishPhp();
|
|
141
247
|
return {
|
|
142
248
|
'main.js': manifestState['main.js'],
|
|
143
249
|
'styles.css': manifestState['styles.css'],
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
# PHP examples
|
|
2
|
-
|
|
3
|
-
Sample handlers for Stagepass projects with `"php": true`. Copy into `api/` (or another path under the project root) before calling them on `https://{{NAME}}.sp`.
|
|
4
|
-
|
|
5
|
-
| File | Purpose |
|
|
6
|
-
| :--- | :--- |
|
|
7
|
-
| `form.php` | POST form handler with length limits and `htmlspecialchars` output |
|
|
8
|
-
| `proxy.php` | HTTPS proxy with an exact-host allowlist (no redirect following) |
|
|
9
|
-
|
|
10
|
-
## Proxy environment
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
export STAGEPASS_PROXY_ALLOWLIST=api.example.com
|
|
14
|
-
# optional:
|
|
15
|
-
export STAGEPASS_PROXY_TOKEN=...
|
|
16
|
-
```
|
|
17
|
-
|
|
18
|
-
Never commit tokens. Keep allowlists exact hosts only (no wildcards, https only).
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
<?php
|
|
2
|
-
/**
|
|
3
|
-
* Example form handler for Stagepass projects.
|
|
4
|
-
*
|
|
5
|
-
* Security notes:
|
|
6
|
-
* - POST only
|
|
7
|
-
* - Input length limits
|
|
8
|
-
* - HTML escaped with htmlspecialchars when rendering
|
|
9
|
-
* - No secrets in this file
|
|
10
|
-
*
|
|
11
|
-
* Copy into /api/ (or another path under the project root) before using on .sp.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
declare(strict_types=1);
|
|
15
|
-
|
|
16
|
-
header('X-Content-Type-Options: nosniff');
|
|
17
|
-
|
|
18
|
-
const MAX_NAME_LEN = 120;
|
|
19
|
-
const MAX_EMAIL_LEN = 254;
|
|
20
|
-
const MAX_MESSAGE_LEN = 4000;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @param mixed $value
|
|
24
|
-
*/
|
|
25
|
-
function field_string($value, int $maxLen): string
|
|
26
|
-
{
|
|
27
|
-
if (!is_string($value)) {
|
|
28
|
-
return '';
|
|
29
|
-
}
|
|
30
|
-
$trimmed = trim($value);
|
|
31
|
-
if (strlen($trimmed) > $maxLen) {
|
|
32
|
-
return substr($trimmed, 0, $maxLen);
|
|
33
|
-
}
|
|
34
|
-
return $trimmed;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function h(string $value): string
|
|
38
|
-
{
|
|
39
|
-
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
|
|
43
|
-
http_response_code(405);
|
|
44
|
-
header('Allow: POST');
|
|
45
|
-
header('Content-Type: application/json; charset=utf-8');
|
|
46
|
-
echo json_encode(['ok' => false, 'error' => 'Method not allowed. Use POST.'], JSON_UNESCAPED_SLASHES);
|
|
47
|
-
exit;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
$name = field_string($_POST['name'] ?? '', MAX_NAME_LEN);
|
|
51
|
-
$email = field_string($_POST['email'] ?? '', MAX_EMAIL_LEN);
|
|
52
|
-
$message = field_string($_POST['message'] ?? '', MAX_MESSAGE_LEN);
|
|
53
|
-
|
|
54
|
-
$errors = [];
|
|
55
|
-
if ($name === '') {
|
|
56
|
-
$errors[] = 'name is required';
|
|
57
|
-
}
|
|
58
|
-
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
59
|
-
$errors[] = 'a valid email is required';
|
|
60
|
-
}
|
|
61
|
-
if ($message === '') {
|
|
62
|
-
$errors[] = 'message is required';
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
$wantsJson = isset($_SERVER['HTTP_ACCEPT'])
|
|
66
|
-
&& str_contains(strtolower((string) $_SERVER['HTTP_ACCEPT']), 'application/json');
|
|
67
|
-
|
|
68
|
-
if ($errors !== []) {
|
|
69
|
-
http_response_code(400);
|
|
70
|
-
if ($wantsJson) {
|
|
71
|
-
header('Content-Type: application/json; charset=utf-8');
|
|
72
|
-
echo json_encode(['ok' => false, 'errors' => $errors], JSON_UNESCAPED_SLASHES);
|
|
73
|
-
exit;
|
|
74
|
-
}
|
|
75
|
-
header('Content-Type: text/html; charset=utf-8');
|
|
76
|
-
echo '<!doctype html><html><body><p>Invalid form:</p><ul>';
|
|
77
|
-
foreach ($errors as $err) {
|
|
78
|
-
echo '<li>' . h($err) . '</li>';
|
|
79
|
-
}
|
|
80
|
-
echo '</ul></body></html>';
|
|
81
|
-
exit;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Demo only: acknowledge receipt. Wire this to mail()/a queue using env secrets.
|
|
85
|
-
$payload = [
|
|
86
|
-
'ok' => true,
|
|
87
|
-
'received' => [
|
|
88
|
-
'name' => $name,
|
|
89
|
-
'email' => $email,
|
|
90
|
-
'message' => $message,
|
|
91
|
-
],
|
|
92
|
-
];
|
|
93
|
-
|
|
94
|
-
if ($wantsJson) {
|
|
95
|
-
header('Content-Type: application/json; charset=utf-8');
|
|
96
|
-
echo json_encode($payload, JSON_UNESCAPED_SLASHES);
|
|
97
|
-
exit;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
header('Content-Type: text/html; charset=utf-8');
|
|
101
|
-
echo '<!doctype html><html><body>';
|
|
102
|
-
echo '<p>Thanks, ' . h($name) . '. We received your message.</p>';
|
|
103
|
-
echo '<p>Email: ' . h($email) . '</p>';
|
|
104
|
-
echo '<pre>' . h($message) . '</pre>';
|
|
105
|
-
echo '</body></html>';
|
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
<?php
|
|
2
|
-
/**
|
|
3
|
-
* Example HTTPS API proxy with a strict host allowlist.
|
|
4
|
-
*
|
|
5
|
-
* Security notes:
|
|
6
|
-
* - GET/POST only
|
|
7
|
-
* - https only, exact host allowlist (no wildcards)
|
|
8
|
-
* - Redirects are not followed to other hosts
|
|
9
|
-
* - Timeouts and response size cap
|
|
10
|
-
* - Secrets (tokens) come from the environment, never from this file
|
|
11
|
-
*
|
|
12
|
-
* Env:
|
|
13
|
-
* STAGEPASS_PROXY_ALLOWLIST Comma-separated exact hosts (required), e.g. api.example.com
|
|
14
|
-
* STAGEPASS_PROXY_TOKEN Optional Bearer token forwarded to the upstream
|
|
15
|
-
*
|
|
16
|
-
* Usage (after copying to /api/proxy.php):
|
|
17
|
-
* GET /api/proxy.php?path=/v1/items
|
|
18
|
-
* The upstream base is https://<first-allowlisted-host> unless ?host= matches the allowlist.
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
declare(strict_types=1);
|
|
22
|
-
|
|
23
|
-
header('X-Content-Type-Options: nosniff');
|
|
24
|
-
header('Content-Type: application/json; charset=utf-8');
|
|
25
|
-
|
|
26
|
-
const PROXY_TIMEOUT_SECONDS = 5;
|
|
27
|
-
const PROXY_MAX_BYTES = 1048576; // 1 MiB
|
|
28
|
-
const PROXY_MAX_PATH_LEN = 512;
|
|
29
|
-
const PROXY_MAX_BODY_LEN = 65536;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* @return list<string>
|
|
33
|
-
*/
|
|
34
|
-
function proxy_allowlist(): array
|
|
35
|
-
{
|
|
36
|
-
$raw = getenv('STAGEPASS_PROXY_ALLOWLIST');
|
|
37
|
-
if (!is_string($raw) || trim($raw) === '') {
|
|
38
|
-
return [];
|
|
39
|
-
}
|
|
40
|
-
$hosts = [];
|
|
41
|
-
foreach (explode(',', $raw) as $part) {
|
|
42
|
-
$host = strtolower(trim($part));
|
|
43
|
-
if ($host === '' || str_contains($host, '/') || str_contains($host, ':') || str_contains($host, '*')) {
|
|
44
|
-
continue;
|
|
45
|
-
}
|
|
46
|
-
if (!preg_match('/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/', $host)) {
|
|
47
|
-
continue;
|
|
48
|
-
}
|
|
49
|
-
$hosts[] = $host;
|
|
50
|
-
}
|
|
51
|
-
return array_values(array_unique($hosts));
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function json_exit(int $status, array $payload): void
|
|
55
|
-
{
|
|
56
|
-
http_response_code($status);
|
|
57
|
-
echo json_encode($payload, JSON_UNESCAPED_SLASHES);
|
|
58
|
-
exit;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
|
62
|
-
if ($method !== 'GET' && $method !== 'POST') {
|
|
63
|
-
header('Allow: GET, POST');
|
|
64
|
-
json_exit(405, ['ok' => false, 'error' => 'Method not allowed.']);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
$allowlist = proxy_allowlist();
|
|
68
|
-
if ($allowlist === []) {
|
|
69
|
-
json_exit(500, [
|
|
70
|
-
'ok' => false,
|
|
71
|
-
'error' => 'Set STAGEPASS_PROXY_ALLOWLIST to a comma-separated list of exact https hosts.',
|
|
72
|
-
]);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
$requestedHost = isset($_GET['host']) ? strtolower(trim((string) $_GET['host'])) : $allowlist[0];
|
|
76
|
-
if (!in_array($requestedHost, $allowlist, true)) {
|
|
77
|
-
json_exit(403, ['ok' => false, 'error' => 'Host is not on the allowlist.']);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
$path = isset($_GET['path']) ? (string) $_GET['path'] : '/';
|
|
81
|
-
if ($path === '' || $path[0] !== '/') {
|
|
82
|
-
json_exit(400, ['ok' => false, 'error' => 'path must start with /.']);
|
|
83
|
-
}
|
|
84
|
-
if (strlen($path) > PROXY_MAX_PATH_LEN || str_contains($path, '\\') || preg_match('/[\x00-\x20\x7f]/', $path) === 1) {
|
|
85
|
-
json_exit(400, ['ok' => false, 'error' => 'Invalid path.']);
|
|
86
|
-
}
|
|
87
|
-
// Block scheme-relative and open-redirect style paths.
|
|
88
|
-
if (str_starts_with($path, '//') || preg_match('#^[a-z][a-z0-9+.-]*:#i', $path) === 1) {
|
|
89
|
-
json_exit(400, ['ok' => false, 'error' => 'Invalid path.']);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
$upstream = 'https://' . $requestedHost . $path;
|
|
93
|
-
$query = $_GET;
|
|
94
|
-
unset($query['host'], $query['path']);
|
|
95
|
-
if ($query !== []) {
|
|
96
|
-
$upstream .= (str_contains($path, '?') ? '&' : '?') . http_build_query($query);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
$body = null;
|
|
100
|
-
if ($method === 'POST') {
|
|
101
|
-
$body = file_get_contents('php://input', false, null, 0, PROXY_MAX_BODY_LEN + 1);
|
|
102
|
-
if ($body === false) {
|
|
103
|
-
json_exit(400, ['ok' => false, 'error' => 'Could not read request body.']);
|
|
104
|
-
}
|
|
105
|
-
if (strlen($body) > PROXY_MAX_BODY_LEN) {
|
|
106
|
-
json_exit(413, ['ok' => false, 'error' => 'Request body too large.']);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
$headers = ['Accept: application/json'];
|
|
111
|
-
$contentType = $_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '';
|
|
112
|
-
if (is_string($contentType) && $contentType !== '' && $method === 'POST') {
|
|
113
|
-
// Only forward a simple media type (no CR/LF injection).
|
|
114
|
-
if (preg_match('/^[a-z0-9!#$&.+\-^_]{1,127}\/[a-z0-9!#$&.+\-^_]{1,127}(?:\s*;\s*charset=utf-8)?$/i', $contentType) === 1) {
|
|
115
|
-
$headers[] = 'Content-Type: ' . $contentType;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
$token = getenv('STAGEPASS_PROXY_TOKEN');
|
|
119
|
-
if (is_string($token) && $token !== '') {
|
|
120
|
-
$headers[] = 'Authorization: Bearer ' . $token;
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
$buffer = '';
|
|
124
|
-
$tooLarge = false;
|
|
125
|
-
$ch = curl_init($upstream);
|
|
126
|
-
if ($ch === false) {
|
|
127
|
-
json_exit(500, ['ok' => false, 'error' => 'Could not start upstream request.']);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
curl_setopt_array($ch, [
|
|
131
|
-
CURLOPT_CUSTOMREQUEST => $method,
|
|
132
|
-
CURLOPT_HTTPHEADER => $headers,
|
|
133
|
-
CURLOPT_RETURNTRANSFER => false,
|
|
134
|
-
// Stream into a buffer and abort once the cap is exceeded (no unbounded memory use).
|
|
135
|
-
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$buffer, &$tooLarge): int {
|
|
136
|
-
if (strlen($buffer) + strlen($chunk) > PROXY_MAX_BYTES) {
|
|
137
|
-
$tooLarge = true;
|
|
138
|
-
return 0;
|
|
139
|
-
}
|
|
140
|
-
$buffer .= $chunk;
|
|
141
|
-
return strlen($chunk);
|
|
142
|
-
},
|
|
143
|
-
CURLOPT_FOLLOWLOCATION => false, // never follow redirects (SSRF / host hop)
|
|
144
|
-
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
|
145
|
-
CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
|
|
146
|
-
CURLOPT_TIMEOUT => PROXY_TIMEOUT_SECONDS,
|
|
147
|
-
CURLOPT_CONNECTTIMEOUT => PROXY_TIMEOUT_SECONDS,
|
|
148
|
-
CURLOPT_SSL_VERIFYPEER => true,
|
|
149
|
-
CURLOPT_SSL_VERIFYHOST => 2,
|
|
150
|
-
CURLOPT_USERAGENT => 'stagepass-php-proxy/1.0',
|
|
151
|
-
]);
|
|
152
|
-
|
|
153
|
-
if ($method === 'POST') {
|
|
154
|
-
curl_setopt($ch, CURLOPT_POSTFIELDS, $body ?? '');
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
curl_exec($ch);
|
|
158
|
-
$errno = curl_errno($ch);
|
|
159
|
-
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
|
160
|
-
curl_close($ch);
|
|
161
|
-
|
|
162
|
-
if ($tooLarge) {
|
|
163
|
-
json_exit(502, ['ok' => false, 'error' => 'Upstream response too large.']);
|
|
164
|
-
}
|
|
165
|
-
if ($errno !== 0) {
|
|
166
|
-
// Do not echo curl details to the client.
|
|
167
|
-
json_exit(502, ['ok' => false, 'error' => 'Upstream request failed.']);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
http_response_code($status >= 100 && $status <= 599 ? $status : 502);
|
|
171
|
-
echo $buffer;
|