@stagepass/cli 2.3.1 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -15
- 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 +103 -32
- package/src/lib/build-script-upgrade.js +249 -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/htaccess-upgrade.js +79 -0
- 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 +24 -16
- package/templates/project/README.md.tmpl +8 -6
- package/templates/project/api/README.md.tmpl +206 -5
- package/templates/project/api/action.php +103 -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 +179 -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/htaccess +7 -0
- package/templates/project/php-private/config.php +24 -0
- package/templates/project/scripts/build.mjs +128 -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
|
@@ -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,130 @@ 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
|
+
/** 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. */
|
|
230
|
+
async function publishPhp() {
|
|
231
|
+
if (watchMode) return;
|
|
232
|
+
let cfg;
|
|
233
|
+
try {
|
|
234
|
+
cfg = JSON.parse(await fs.readFile(path.join(root, 'stagepass.json'), 'utf8'));
|
|
235
|
+
} catch {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (!cfg || cfg.php !== true) return;
|
|
239
|
+
await copyFiltered(path.join(root, 'api'), path.join(distDir, 'api'));
|
|
240
|
+
await publishRootHtaccess();
|
|
241
|
+
const configSrc = path.join(root, '.php', 'config.php');
|
|
242
|
+
let st;
|
|
243
|
+
try {
|
|
244
|
+
st = await fs.lstat(configSrc);
|
|
245
|
+
} catch {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (!st.isFile()) return;
|
|
249
|
+
const destDir = path.join(distDir, '.php');
|
|
250
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
251
|
+
await fs.copyFile(configSrc, path.join(destDir, 'config.php'));
|
|
252
|
+
}
|
|
253
|
+
|
|
137
254
|
async function buildOnce() {
|
|
138
255
|
await ensureDist();
|
|
256
|
+
const prev = watchMode ? null : await priorHashNames();
|
|
139
257
|
await buildJsOnce();
|
|
140
258
|
await buildCss();
|
|
259
|
+
if (prev) await removeStaleHashes(prev);
|
|
260
|
+
await publishPhp();
|
|
141
261
|
return {
|
|
142
262
|
'main.js': manifestState['main.js'],
|
|
143
263
|
'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;
|