@stagepass/cli 2.4.0 → 2.5.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.
@@ -1,174 +1,29 @@
1
- # Stagepass PHP boilerplate
1
+ # Stagepass PHP
2
2
 
3
- Plain PHP 8.2 or newer. No framework. No Composer. No mail.
3
+ Plain PHP 8.2 or newer. No framework, no Composer, no mail. The agent guide is `AGENTS.stagepass.md` (section PHP). Longer notes: [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/).
4
4
 
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.
5
+ `api/action.php` is the only public entry. Register actions in `api/actions.php`. Handlers live in `api/actions/`.
6
6
 
7
- A longer guide is planned at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/). That page is not live yet.
7
+ ## Setup
8
8
 
9
- ## Where to edit
9
+ Copy `api/.env.example` to `.env` in the project root (the folder that contains `api/`). Set `ALLOWED_ORIGINS` to exact origins, including `https://{{NAME}}.sp`. Do not commit `.env`.
10
10
 
11
- Edit these:
11
+ That folder is the document root locally, and `dist/` after `stagepass build`. From Webflow, `window.location.origin` is the Webflow host and does not run PHP. Call the PHP host with its absolute URL, for example `https://php.example.com/api/action.php`.
12
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.
13
+ Prefer `stagepass dev` or the linked `.sp` domain. `php -S 127.0.0.1:8080 -t .` matches `/api/action.php` but does not hide `/.env`. Do not point it at a folder that already contains a real `.env`.
46
14
 
47
- `APP_ENV=local` turns on a hidden `boom` action used only to test error handling. Leave `APP_ENV=production` on a live host.
15
+ Apache uses the project `.htaccess`. nginx does not. Put this in the server block before `location ~ \.php$`:
48
16
 
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;
17
+ ```nginx
18
+ location ~* /\.(?!well-known\/) {
19
+ deny all;
60
20
  }
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
21
  ```
85
22
 
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
- ```
23
+ ## New action
171
24
 
172
- Then: `curl 'http://127.0.0.1:8080/api/action.php?action=ping'`
25
+ The recipe in `AGENTS.stagepass.md` is three steps:
173
26
 
174
- On a linked Stagepass domain the same file is reached at `https://your-project.sp/api/action.php`.
27
+ 1. Add `api/actions/<name>.php` that returns a callable. Validate with `validate_required`, `validate_email`, and `validate_max_length`. Call another service with curl and a timeout. Read secrets with `env_string` and no default. Log upstream failures with `error_log` and answer with `respond_error`.
28
+ 2. Register the name in `action_catalog()` (`methods`, `honeypot`, `rate_limit`, `origin`).
29
+ 3. Call `/api/action.php` with `action` set to that name. Do not add another public `.php` file next to `action.php`.
@@ -40,6 +40,9 @@ if ($method === 'OPTIONS') {
40
40
  if ($origin === '' || !origin_is_allowed($origin, $allowedOrigins)) {
41
41
  respond_fail(['origin' => 'Origin is not allowed.'], 'Origin is not allowed.', 403);
42
42
  }
43
+ if (!headers_sent()) {
44
+ header_remove('X-Powered-By');
45
+ }
43
46
  http_response_code(204);
44
47
  header('Content-Length: 0');
45
48
  exit;
@@ -56,6 +59,10 @@ if ($action === '' || !isset($catalog[$action])) {
56
59
 
57
60
  $spec = $catalog[$action];
58
61
  $allowedMethods = $spec['methods'];
62
+ $env = (string) ($config['env'] ?? 'production');
63
+ $limitMax = (int) $config['rate_limit_max'];
64
+ $limitWindow = (int) $config['rate_limit_window'];
65
+ $rateLimit = $spec['rate_limit'] && $limitMax > 0 && $limitWindow > 0;
59
66
 
60
67
  if (!in_array($method, $allowedMethods, true)) {
61
68
  if (!headers_sent()) {
@@ -79,9 +86,14 @@ if ($allowedOrigins === [] && $originRequired) {
79
86
  respond_fail(['origin' => 'No origins are configured.'], 'Origin is not allowed.', 403);
80
87
  }
81
88
 
82
- if ($spec['rate_limit'] && !rate_limit_allows(client_ip(), $action, (int) $config['rate_limit_max'], (int) $config['rate_limit_window'])) {
89
+ // Storage faults apply only after method and origin checks.
90
+ if ($rateLimit && !rate_limit_storage_available($env)) {
91
+ $rateLimit = false;
92
+ }
93
+
94
+ if ($rateLimit && !rate_limit_allows(client_ip($config), $action, $limitMax, $limitWindow, $env)) {
83
95
  if (!headers_sent()) {
84
- header('Retry-After: ' . (string) $config['rate_limit_window']);
96
+ header('Retry-After: ' . (string) $limitWindow);
85
97
  }
86
98
  respond_fail(['rate_limit' => 'Too many requests. Try again later.'], 'Too many requests.', 429);
87
99
  }
@@ -2,7 +2,9 @@
2
2
  # This is the main place to configure origins, limits, and the environment.
3
3
  # Never commit real secrets. This boilerplate does not send mail.
4
4
 
5
- # "local" or "production". The "boom" test action is only registered when local.
5
+ # "local" registers the boom test action (exact spelling).
6
+ # Rate-limit storage faults fail open only for local, development, or dev
7
+ # (trimmed, any case). Empty and every other value are HTTP 503.
6
8
  APP_ENV=production
7
9
 
8
10
  # Exact origins allowed to call POST actions and to receive CORS headers.
@@ -23,3 +25,11 @@ RATE_LIMIT_WINDOW=60
23
25
  MAX_BODY_BYTES=65536
24
26
 
25
27
  APP_TIMEZONE=Europe/Berlin
28
+
29
+ # Comma-separated proxy IPs and CIDRs (IPv4 or IPv6). Forwarded headers are
30
+ # ignored unless REMOTE_ADDR is in this list. Empty keeps REMOTE_ADDR only.
31
+ # TRUSTED_PROXIES=10.0.0.0/8,192.168.1.1,2001:db8:1::/48
32
+
33
+ # Header read when the peer is a trusted proxy: x-forwarded-for (default)
34
+ # or forwarded (RFC 7239). Other names are ignored.
35
+ # TRUSTED_PROXY_HEADER=x-forwarded-for
@@ -22,9 +22,8 @@ function project_root(): string
22
22
  }
23
23
 
24
24
  /**
25
- * Hidden directory for config and rate-limit files.
26
- *
27
- * On Stagepass, Caddy already returns 404 for any path segment starting with ".".
25
+ * Config and rate-limit directory, inside the document root (the folder that contains api/).
26
+ * Deny hidden paths with the shipped .htaccess, the nginx snippet in api/README.md, or Caddy locally.
28
27
  */
29
28
  function private_dir(): string
30
29
  {
@@ -130,7 +129,7 @@ function env_list(string $key): array
130
129
  }
131
130
 
132
131
  /**
133
- * Load configuration from .env and an optional PHP config file outside the public root.
132
+ * Load configuration from the project-root .env, .php/.env, and optional .php/config.php.
134
133
  *
135
134
  * @return array{
136
135
  * env: string,
@@ -139,7 +138,9 @@ function env_list(string $key): array
139
138
  * rate_limit_max: int,
140
139
  * rate_limit_window: int,
141
140
  * max_body_bytes: int,
142
- * timezone: string
141
+ * timezone: string,
142
+ * trusted_proxies: list<string>,
143
+ * trusted_proxy_header: string
143
144
  * }
144
145
  */
145
146
  function load_config(): array
@@ -155,6 +156,8 @@ function load_config(): array
155
156
  'rate_limit_window' => env_int('RATE_LIMIT_WINDOW', 60),
156
157
  'max_body_bytes' => env_int('MAX_BODY_BYTES', 65536),
157
158
  'timezone' => env_string('APP_TIMEZONE', 'Europe/Berlin'),
159
+ 'trusted_proxies' => env_list('TRUSTED_PROXIES'),
160
+ 'trusted_proxy_header' => env_string('TRUSTED_PROXY_HEADER', 'x-forwarded-for'),
158
161
  ];
159
162
 
160
163
  $file = null;
@@ -25,10 +25,373 @@ function request_origin(): string
25
25
  return trim((string) ($_SERVER['HTTP_ORIGIN'] ?? ''));
26
26
  }
27
27
 
28
- function client_ip(): string
28
+ function client_ip(?array $config = null): string
29
29
  {
30
- $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
31
- return $ip !== '' ? $ip : '0.0.0.0';
30
+ if ($config === null) {
31
+ $config = load_config();
32
+ }
33
+
34
+ $remoteRaw = trim((string) ($_SERVER['REMOTE_ADDR'] ?? ''));
35
+ $remote = normalize_ip($remoteRaw);
36
+ if ($remote === null) {
37
+ return $remoteRaw !== '' ? $remoteRaw : '0.0.0.0';
38
+ }
39
+
40
+ $rules = compile_trusted_proxies(trusted_proxy_entries($config));
41
+ if ($rules === [] || !ip_in_trusted($remote, $rules)) {
42
+ return $remote;
43
+ }
44
+
45
+ $header = trusted_proxy_header_name($config);
46
+ if ($header === null) {
47
+ error_log('stagepass-php: unknown TRUSTED_PROXY_HEADER; using REMOTE_ADDR.');
48
+ return $remote;
49
+ }
50
+
51
+ $serverKey = $header === 'forwarded' ? 'HTTP_FORWARDED' : 'HTTP_X_FORWARDED_FOR';
52
+ $raw = trim((string) ($_SERVER[$serverKey] ?? ''));
53
+ if ($raw === '') {
54
+ return $remote;
55
+ }
56
+
57
+ // Stop at the first untrusted hop. Left of it is ignored; a bad hop in this suffix falls back.
58
+ $chosen = select_client_hop($raw, $header, $rules);
59
+ if ($chosen === null) {
60
+ error_log('stagepass-php: invalid proxy hop; using REMOTE_ADDR.');
61
+ return $remote;
62
+ }
63
+ return $chosen;
64
+ }
65
+
66
+ function trusted_proxy_entries(array $config): array
67
+ {
68
+ if (!array_key_exists('trusted_proxies', $config)) {
69
+ return [];
70
+ }
71
+ $raw = $config['trusted_proxies'];
72
+ if (is_string($raw)) {
73
+ $split = preg_split('/\s*,\s*/', $raw);
74
+ $raw = $split === false ? [] : $split;
75
+ }
76
+ if (!is_array($raw)) {
77
+ error_log('stagepass-php: ignoring invalid trusted proxy list.');
78
+ return [];
79
+ }
80
+ $entries = [];
81
+ foreach ($raw as $entry) {
82
+ if (!is_string($entry)) {
83
+ log_invalid_proxy_entry('');
84
+ continue;
85
+ }
86
+ $entries[] = $entry;
87
+ }
88
+ return $entries;
89
+ }
90
+
91
+ function trusted_proxy_header_name(array $config): ?string
92
+ {
93
+ $name = strtolower(trim((string) ($config['trusted_proxy_header'] ?? 'x-forwarded-for')));
94
+ if ($name === '' || $name === 'x-forwarded-for') {
95
+ return 'x-forwarded-for';
96
+ }
97
+ if ($name === 'forwarded') {
98
+ return 'forwarded';
99
+ }
100
+ return null;
101
+ }
102
+
103
+ function normalize_ip(string $value): ?string
104
+ {
105
+ $value = trim($value);
106
+ if (filter_var($value, FILTER_VALIDATE_IP) === false) {
107
+ return null;
108
+ }
109
+ $packed = inet_pton($value);
110
+ if ($packed === false) {
111
+ return null;
112
+ }
113
+ $text = inet_ntop($packed);
114
+ return $text === false ? null : $text;
115
+ }
116
+
117
+ function compile_trusted_proxies(array $entries): array
118
+ {
119
+ $rules = [];
120
+ foreach ($entries as $entry) {
121
+ $entry = trim($entry);
122
+ if ($entry === '') {
123
+ continue;
124
+ }
125
+ $addr = $entry;
126
+ $bits = null;
127
+ if (str_contains($entry, '/')) {
128
+ [$addr, $prefix] = explode('/', $entry, 2);
129
+ if ($prefix === '' || preg_match('/^\d+$/', $prefix) !== 1) {
130
+ log_invalid_proxy_entry($entry);
131
+ continue;
132
+ }
133
+ $bits = (int) $prefix;
134
+ }
135
+ $norm = normalize_ip(trim($addr));
136
+ if ($norm === null) {
137
+ log_invalid_proxy_entry($entry);
138
+ continue;
139
+ }
140
+ $packed = inet_pton($norm);
141
+ if ($packed === false) {
142
+ log_invalid_proxy_entry($entry);
143
+ continue;
144
+ }
145
+ $max = strlen($packed) * 8;
146
+ if ($bits === null) {
147
+ $bits = $max;
148
+ }
149
+ if ($bits > $max) {
150
+ log_invalid_proxy_entry($entry);
151
+ continue;
152
+ }
153
+ $rules[] = ['packed' => $packed, 'bits' => $bits];
154
+ }
155
+ return $rules;
156
+ }
157
+
158
+ function log_invalid_proxy_entry(string $entry): void
159
+ {
160
+ static $seen = [];
161
+ $safe = preg_replace('/[^\x20-\x7E]/', '', $entry) ?? '';
162
+ $safe = substr($safe, 0, 80);
163
+ if (isset($seen[$safe])) {
164
+ return;
165
+ }
166
+ $seen[$safe] = true;
167
+ error_log('stagepass-php: ignoring invalid trusted proxy entry: ' . $safe);
168
+ }
169
+
170
+ function ip_in_trusted(string $ip, array $rules): bool
171
+ {
172
+ $packed = inet_pton($ip);
173
+ if ($packed === false) {
174
+ return false;
175
+ }
176
+ foreach ($rules as $rule) {
177
+ if (strlen($packed) !== strlen($rule['packed'])) {
178
+ continue;
179
+ }
180
+ if (ip_prefix_match($packed, $rule['packed'], $rule['bits'])) {
181
+ return true;
182
+ }
183
+ }
184
+ return false;
185
+ }
186
+
187
+ function ip_prefix_match(string $ip, string $network, int $bits): bool
188
+ {
189
+ $full = intdiv($bits, 8);
190
+ if ($full > 0 && substr($ip, 0, $full) !== substr($network, 0, $full)) {
191
+ return false;
192
+ }
193
+ $rest = $bits % 8;
194
+ if ($rest === 0) {
195
+ return true;
196
+ }
197
+ $mask = (0xff << (8 - $rest)) & 0xff;
198
+ return (ord($ip[$full]) & $mask) === (ord($network[$full]) & $mask);
199
+ }
200
+
201
+ function ip_from_hop(string $hop): ?string
202
+ {
203
+ $hop = trim($hop);
204
+ if ($hop === '') {
205
+ return null;
206
+ }
207
+ if ($hop[0] === '"' && str_ends_with($hop, '"') && strlen($hop) >= 2) {
208
+ $hop = substr($hop, 1, -1);
209
+ }
210
+ if (strcasecmp($hop, 'unknown') === 0 || str_starts_with($hop, '_')) {
211
+ return null;
212
+ }
213
+ if ($hop[0] === '[') {
214
+ $end = strpos($hop, ']');
215
+ if ($end === false) {
216
+ return null;
217
+ }
218
+ $ip = substr($hop, 1, $end - 1);
219
+ $rest = substr($hop, $end + 1);
220
+ if ($rest !== '' && preg_match('/^:\d{1,5}$/', $rest) !== 1) {
221
+ return null;
222
+ }
223
+ return normalize_ip($ip);
224
+ }
225
+ if (preg_match('/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/', $hop, $match) === 1) {
226
+ return normalize_ip($match[1]);
227
+ }
228
+ return normalize_ip($hop);
229
+ }
230
+
231
+ function select_client_hop(string $header, string $kind, array $rules): ?string
232
+ {
233
+ // Only the rightmost hops are read, so a long prefix cannot change the result.
234
+ $maxHops = 32;
235
+ $maxScan = 8192;
236
+ $maxHop = 512;
237
+ $end = strlen($header);
238
+ $scanned = 0;
239
+ $seen = 0;
240
+ $leftmost = null;
241
+ while ($end > 0 && $seen < $maxHops && $scanned < $maxScan) {
242
+ $budget = $maxScan - $scanned;
243
+ $hop = $kind === 'forwarded'
244
+ ? forwarded_hop_before($header, $end, $maxHop, $budget)
245
+ : xff_hop_before($header, $end, $maxHop, $budget);
246
+ if ($hop['kind'] === 'invalid') {
247
+ return null;
248
+ }
249
+ $seen++;
250
+ $scanned += $hop['consumed'];
251
+ $end = $hop['end'];
252
+ $ip = $kind === 'forwarded' ? ip_from_forwarded_element($hop['text']) : ip_from_hop($hop['text']);
253
+ if ($ip === null) {
254
+ return null;
255
+ }
256
+ $leftmost = $ip;
257
+ if (!ip_in_trusted($ip, $rules)) {
258
+ return $ip;
259
+ }
260
+ if ($hop['kind'] === 'start') {
261
+ break;
262
+ }
263
+ }
264
+ return $leftmost;
265
+ }
266
+
267
+ function xff_hop_before(string $header, int $end, int $maxHop, int $budget): array
268
+ {
269
+ $i = $end - 1;
270
+ $n = 0;
271
+ while ($i >= 0 && $header[$i] !== ',') {
272
+ $n++;
273
+ if ($n > $maxHop || $n > $budget) {
274
+ return ['kind' => 'invalid', 'text' => '', 'end' => $end, 'consumed' => $n];
275
+ }
276
+ $i--;
277
+ }
278
+ $start = $i + 1;
279
+ return [
280
+ 'kind' => $i < 0 ? 'start' : 'next',
281
+ 'text' => substr($header, $start, $end - $start),
282
+ 'end' => $i < 0 ? 0 : $i,
283
+ 'consumed' => $end - ($i < 0 ? 0 : $i),
284
+ ];
285
+ }
286
+
287
+ function forwarded_hop_before(string $header, int $end, int $maxHop, int $budget): array
288
+ {
289
+ $i = $end - 1;
290
+ $n = 0;
291
+ $inQuote = false;
292
+ while ($i >= 0) {
293
+ $n++;
294
+ if ($n > $maxHop || $n > $budget) {
295
+ return ['kind' => 'invalid', 'text' => '', 'end' => $end, 'consumed' => $n];
296
+ }
297
+ $ch = $header[$i];
298
+ if ($ch === '"') {
299
+ $slashes = 0;
300
+ $j = $i - 1;
301
+ while ($j >= 0 && $header[$j] === '\\' && $slashes < 8) {
302
+ $slashes++;
303
+ $j--;
304
+ }
305
+ if ($slashes % 2 === 0) {
306
+ $inQuote = !$inQuote;
307
+ }
308
+ } elseif ($ch === ',' && !$inQuote) {
309
+ return [
310
+ 'kind' => 'next',
311
+ 'text' => substr($header, $i + 1, $end - $i - 1),
312
+ 'end' => $i,
313
+ 'consumed' => $end - $i,
314
+ ];
315
+ }
316
+ $i--;
317
+ }
318
+ if ($inQuote) {
319
+ return ['kind' => 'invalid', 'text' => '', 'end' => 0, 'consumed' => $n];
320
+ }
321
+ return [
322
+ 'kind' => 'start',
323
+ 'text' => substr($header, 0, $end),
324
+ 'end' => 0,
325
+ 'consumed' => $end,
326
+ ];
327
+ }
328
+
329
+ function ip_from_forwarded_element(string $element): ?string
330
+ {
331
+ if (trim($element) === '') {
332
+ return null;
333
+ }
334
+ $value = forwarded_for_value($element);
335
+ if ($value === null || $value === '') {
336
+ return null;
337
+ }
338
+ return ip_from_hop($value);
339
+ }
340
+
341
+ function forwarded_for_value(string $element): ?string
342
+ {
343
+ $len = strlen($element);
344
+ $i = 0;
345
+ $found = null;
346
+ while ($i < $len) {
347
+ while ($i < $len && ($element[$i] === ' ' || $element[$i] === "\t" || $element[$i] === ';')) {
348
+ $i++;
349
+ }
350
+ if ($i >= $len) {
351
+ break;
352
+ }
353
+ $start = $i;
354
+ while ($i < $len && $element[$i] !== '=' && $element[$i] !== ';') {
355
+ $i++;
356
+ }
357
+ if ($i >= $len || $element[$i] !== '=') {
358
+ return null;
359
+ }
360
+ $name = strtolower(trim(substr($element, $start, $i - $start)));
361
+ $i++;
362
+ if ($i < $len && $element[$i] === '"') {
363
+ $i++;
364
+ $val = '';
365
+ $closed = false;
366
+ while ($i < $len) {
367
+ if ($element[$i] === '\\' && $i + 1 < $len) {
368
+ $val .= $element[$i + 1];
369
+ $i += 2;
370
+ continue;
371
+ }
372
+ if ($element[$i] === '"') {
373
+ $i++;
374
+ $closed = true;
375
+ break;
376
+ }
377
+ $val .= $element[$i];
378
+ $i++;
379
+ }
380
+ if (!$closed) {
381
+ return null;
382
+ }
383
+ } else {
384
+ $start = $i;
385
+ while ($i < $len && $element[$i] !== ';') {
386
+ $i++;
387
+ }
388
+ $val = trim(substr($element, $start, $i - $start));
389
+ }
390
+ if ($name === 'for' && $found === null) {
391
+ $found = $val;
392
+ }
393
+ }
394
+ return $found;
32
395
  }
33
396
 
34
397
  /**