@stagepass/cli 2.4.1 → 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,208 +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 at [https://stagepass.one/docs/php/](https://stagepass.one/docs/php/). Copy `api/.env.example` to `.env` in the project root, or use `.php/.env`. `stagepass build` never copies `.env` into `dist`.
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 Optional overrides, inside the document root (the folder that contains api/)
37
- .php/rate-limit/ Runtime files, not copied to dist. Deny hidden paths on the host
38
- .htaccess Apache deny for hidden paths (shipped)
39
- .env Local environment (do not commit)
40
- ```
41
-
42
- ## Configure
43
-
44
- 1. Copy `api/.env.example` to `.env` in the project root (the folder that contains `api/`).
45
- 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`.
46
- 3. Keep `.env` out of git. The document root is the folder that contains `api/` (the project root locally, `dist/` after `stagepass build`). Caddy returns 404 for any path segment that starts with `.`. Since 2.4.1 this starter ships a web-root `.htaccess` (Apache needs `AllowOverride All` and `mod_rewrite`). `stagepass upgrade` writes that file when `stagepass.json` has `"php": true` and the project root has none. An existing `.htaccess` is left unchanged. If it has no `RewriteRule "(^|/)\." - [F]` line, add that rule yourself. Published CLI 2.4.0 does not write the file. `stagepass build` copies the project `.htaccess` into `dist/` and does not replace an existing project `.htaccess`. It does not copy `.env`, `.php/.env`, or `.php/rate-limit/`. nginx does not read `.htaccess`. Put this in the server block before `location ~ \.php$`:
47
-
48
- ```nginx
49
- location ~* /\.(?!well-known\/) {
50
- deny all;
51
- }
52
- ```
53
-
54
- Prefer real environment variables on the host so a `.env` file is not required in the web root.
55
- 4. `stagepass build` copies `api/` to `dist/api/`, `.php/config.php` to `dist/.php/config.php`, and the project `.htaccess` to `dist/.htaccess`. Upload `dist/`. The public URL stays `/api/action.php`.
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`.
56
14
 
57
- `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$`:
58
16
 
59
- ## Add a new action
60
-
61
- 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.
62
-
63
- ```php
64
- <?php
65
- declare(strict_types=1);
66
-
67
- if (!defined('STAGEPASS_PHP_ENTRY')) {
68
- http_response_code(404);
69
- exit;
17
+ ```nginx
18
+ location ~* /\.(?!well-known\/) {
19
+ deny all;
70
20
  }
71
-
72
- return static function (array $input, array $config): array {
73
- $errors = [];
74
- validate_required($input, 'email', $errors);
75
- validate_email($input, 'email', $errors);
76
- if ($errors !== []) {
77
- throw new ValidationException($errors);
78
- }
79
- // Your logic here.
80
- return ['subscribed' => true];
81
- };
82
- ```
83
-
84
- 2. Register the name in `api/actions.php`:
85
-
86
- ```php
87
- 'newsletter' => [
88
- 'file' => 'newsletter.php',
89
- 'methods' => ['POST'],
90
- 'honeypot' => true,
91
- 'rate_limit' => true,
92
- 'origin' => 'required',
93
- ],
94
- ```
95
-
96
- 3. Call it from JavaScript with `action: 'newsletter'`. Do not add a second public PHP file unless you have a strong reason.
97
-
98
- ## Call it from JavaScript
99
-
100
- `sp.resolveLocalUrl` returns a local HTTPS URL only during an active `.sp` session, otherwise `''`. On a Webflow page `window.location.origin` is the Webflow host, and Webflow does not run PHP. There is no helper for the public PHP base URL (`origin` and `production` in `stagepass.json` are Webflow hosts). Use the absolute URL of the PHP host, for example `https://php.example.com/api/action.php`.
101
-
102
- ```js
103
- const path = '/api/action.php';
104
- const phpHost = 'https://php.example.com';
105
- const local = sp.vars.isLocal && sp.resolveLocalUrl(path);
106
- const url = local || phpHost + path;
107
-
108
- const response = await fetch(url, {
109
- method: 'POST',
110
- headers: {
111
- Accept: 'application/json',
112
- 'Content-Type': 'application/json',
113
- },
114
- body: JSON.stringify({
115
- action: 'contact',
116
- name: 'Ada Lovelace',
117
- email: 'ada@example.com',
118
- message: 'Hello',
119
- website: '', // honeypot; leave empty, hide this field in CSS
120
- }),
121
- });
122
-
123
- const result = await response.json();
124
- // result.status is "success", "fail", or "error"
125
- if (result.status === 'success') {
126
- console.log('Saved', result.data);
127
- } else {
128
- console.warn(result.message, result.data);
129
- }
130
- ```
131
-
132
- A simple GET check:
133
-
134
- ```js
135
- const url =
136
- (sp.vars.isLocal && sp.resolveLocalUrl('/api/action.php')) ||
137
- 'https://php.example.com/api/action.php';
138
-
139
- const result = await fetch(url + '?action=ping', {
140
- headers: { Accept: 'application/json' },
141
- }).then((r) => r.json());
142
- ```
143
-
144
- `contact.php` validates a JSON or form POST and does not send mail. A native Webflow form needs its own submit listener. There is no shipped helper for that.
145
-
146
- ```js
147
- form.addEventListener('submit', async (event) => {
148
- event.preventDefault();
149
- const url =
150
- (sp.vars.isLocal && sp.resolveLocalUrl('/api/action.php')) ||
151
- 'https://php.example.com/api/action.php';
152
- await fetch(url, {
153
- method: 'POST',
154
- headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
155
- body: JSON.stringify({
156
- action: 'contact',
157
- name: form.elements.name.value,
158
- email: form.elements.email.value,
159
- message: form.elements.message.value,
160
- website: '',
161
- }),
162
- });
163
- });
164
- ```
165
-
166
- ## Response shape
167
-
168
- Every response is JSON with `status`, `data`, and `message`, plus a matching HTTP status code.
169
-
170
- ```json
171
- { "status": "success", "data": { "pong": true }, "message": null }
172
- ```
173
-
174
- ```json
175
- {
176
- "status": "fail",
177
- "data": { "email": "A valid email is required." },
178
- "message": "Validation failed."
179
- }
180
- ```
181
-
182
- ```json
183
- {
184
- "status": "error",
185
- "data": null,
186
- "message": "An unexpected error occurred. Try again later."
187
- }
188
- ```
189
-
190
- `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.
191
-
192
- ## Security defaults
193
-
194
- 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/`. `rate_limit_allows()` is fail-open: if the directory cannot be created, the file cannot be opened, `flock` fails, or the limiter throws, the request is allowed. Directory and file failures, and thrown errors, are logged. A failed `flock` allows the request and does not write its own log line. `client_ip()` uses only `REMOTE_ADDR`, never `X-Forwarded-For`. Do not trust that header without a proxy allowlist. Behind a reverse proxy or CDN every visitor can share one address, so the limit applies to everyone together. This stays fail-open.
195
-
196
- ## Local PHP server
197
-
198
- From the project root (the folder that contains `api/`):
199
-
200
- ```bash
201
- php -S 127.0.0.1:8080 -t .
202
21
  ```
203
22
 
204
- Then: `curl 'http://127.0.0.1:8080/api/action.php?action=ping'`
23
+ ## New action
205
24
 
206
- `php -S 127.0.0.1:8080 -t api` serves `/action.php` and does not match this layout. PHP's built-in server does not return 404 for hidden paths the way Caddy does (`/.env`, `/.php/`). Do not point `php -S -t .` at a folder that already contains a real `.env`. Prefer `stagepass dev` or the linked `.sp` domain.
25
+ The recipe in `AGENTS.stagepass.md` is three steps:
207
26
 
208
- 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`.
@@ -59,6 +59,10 @@ if ($action === '' || !isset($catalog[$action])) {
59
59
 
60
60
  $spec = $catalog[$action];
61
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;
62
66
 
63
67
  if (!in_array($method, $allowedMethods, true)) {
64
68
  if (!headers_sent()) {
@@ -82,9 +86,14 @@ if ($allowedOrigins === [] && $originRequired) {
82
86
  respond_fail(['origin' => 'No origins are configured.'], 'Origin is not allowed.', 403);
83
87
  }
84
88
 
85
- 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)) {
86
95
  if (!headers_sent()) {
87
- header('Retry-After: ' . (string) $config['rate_limit_window']);
96
+ header('Retry-After: ' . (string) $limitWindow);
88
97
  }
89
98
  respond_fail(['rate_limit' => 'Too many requests. Try again later.'], 'Too many requests.', 429);
90
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
@@ -138,7 +138,9 @@ function env_list(string $key): array
138
138
  * rate_limit_max: int,
139
139
  * rate_limit_window: int,
140
140
  * max_body_bytes: int,
141
- * timezone: string
141
+ * timezone: string,
142
+ * trusted_proxies: list<string>,
143
+ * trusted_proxy_header: string
142
144
  * }
143
145
  */
144
146
  function load_config(): array
@@ -154,6 +156,8 @@ function load_config(): array
154
156
  'rate_limit_window' => env_int('RATE_LIMIT_WINDOW', 60),
155
157
  'max_body_bytes' => env_int('MAX_BODY_BYTES', 65536),
156
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'),
157
161
  ];
158
162
 
159
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
  /**