Skip to content

Commit 523d65c

Browse files
committed
added CLAUDE.md
1 parent 0aa50b1 commit 523d65c

2 files changed

Lines changed: 352 additions & 0 deletions

File tree

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
.gitattributes export-ignore
22
.github/ export-ignore
33
.gitignore export-ignore
4+
CLAUDE.md export-ignore
45
ncs.* export-ignore
56
phpstan*.neon export-ignore
67
src/**/*.latte export-ignore

CLAUDE.md

Lines changed: 351 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,351 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Project Overview
6+
7+
**Nette HTTP Component** - A standalone PHP library providing HTTP abstraction for request/response handling, URL manipulation, session management, and file uploads. Part of the Nette Framework ecosystem but usable independently.
8+
9+
- **PHP Version**: 8.3 - 8.5
10+
- **Package**: `nette/http`
11+
12+
## Essential Commands
13+
14+
### Running Tests
15+
16+
```bash
17+
# Run all tests
18+
vendor/bin/tester tests -s
19+
20+
# Run specific test file
21+
php tests/Http/Request.files.phpt
22+
23+
# Run tests in specific directory
24+
vendor/bin/tester tests/Http -s
25+
```
26+
27+
### Static Analysis
28+
29+
```bash
30+
# Run PHPStan
31+
composer phpstan
32+
33+
# Or directly
34+
vendor/bin/phpstan analyse
35+
```
36+
37+
## Core Architecture
38+
39+
### Immutability Pattern
40+
41+
The codebase uses a sophisticated immutability strategy:
42+
43+
- **`Request`** - Immutable HTTP request with single wither method `withUrl()`
44+
- **`Response`** - Mutable for managing response state (headers, cookies, status)
45+
- **`UrlImmutable`** - Immutable URL with wither methods (`withHost()`, `withPath()`, etc.)
46+
- **`Url`** - Mutable URL with setters for flexible building
47+
- **`UrlScript`** - Extends UrlImmutable with script path information
48+
49+
**Design principle**: Data objects (Request) are immutable for integrity; state managers (Response, Session) are mutable for practical management.
50+
51+
### Security-First Design
52+
53+
Input sanitization is mandatory, not optional:
54+
55+
1. **RequestFactory** sanitizes ALL input:
56+
- Removes invalid UTF-8 sequences
57+
- Strips control characters (except tab, newline, carriage return)
58+
- Validates with regex: `[\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}]`
59+
60+
2. **Secure defaults everywhere**:
61+
- Cookies are `httpOnly` by default
62+
- `SameSite=Lax` by default
63+
- Session uses strict mode and one-time cookies only
64+
- HTTPS auto-detection via proxy configuration
65+
66+
3. **FileUpload** security:
67+
- Content-based MIME detection (not client-provided)
68+
- `getSanitizedName()` removes dangerous characters
69+
- Documentation warns against trusting `getUntrustedName()`
70+
71+
### Key Components
72+
73+
#### Request (`src/Http/Request.php`)
74+
- Immutable HTTP request representation
75+
- Type-safe access to GET/POST/COOKIE/FILES/headers
76+
- AJAX detection, language detection
77+
- **Request origin checking**: `isFrom()` is the current API — checks `Sec-Fetch-Site`/`Sec-Fetch-Dest`/`Sec-Fetch-User` against the `FetchSite`/`FetchDest` enums (`src/Http/enums.php`), serving as CSRF-like protection for forms and signals. Falls back to the `SameSite=Strict` cookie (`_nss`, formerly `nette-samesite`) for browsers without Sec-Fetch (Safari < 16.4)
78+
- `isSameSite()` is **deprecated** — it now delegates to `isFrom([FetchSite::SameSite, FetchSite::SameOrigin])`
79+
- Sanitized by RequestFactory before construction
80+
- **Origin detection**: `getOrigin()` returns scheme + host + port for CORS validation
81+
- **Basic Auth**: `getBasicCredentials()` returns `[user, password]` array
82+
- **File access**: `getFile(['my-form', 'details', 'avatar'])` accepts array of keys for nested structures
83+
- **`getRemoteHost()` is deprecated** (v3.4.0) — it now always returns `null`. Reverse DNS was slow, unreliable and a privacy footgun. Resolve the hostname yourself from `getRemoteAddress()` if you really need it
84+
- **Warning**: Browsers don't send URL fragments to the server (`$url->getFragment()` returns empty string)
85+
86+
#### Response (`src/Http/Response.php`)
87+
- Mutable HTTP response management
88+
- Header manipulation (set/add/delete)
89+
- Cookie handling with security defaults — pass the `SameSite` enum (`SameSite::Lax`, `SameSite::Strict`, `SameSite::None`) to `setCookie()`. The old `IResponse::SameSiteLax/SameSiteStrict/SameSiteNone` string constants are **deprecated**
90+
- **CHIPS / partitioned cookies**: `setCookie()` has a `bool $partitioned = false` parameter; setting it (or `SameSite::None`) forces the `Secure` attribute
91+
- **`Max-Age`** (v3.4.0): `setCookie()` emits a `Max-Age` attribute (takes precedence over `expires`, ignores client clock). It now builds the `Set-Cookie` header itself instead of delegating to PHP's `setcookie()`. Passing integer `0` as the expiration is **deprecated** — use `null` for a session cookie
92+
- Redirect, cache control, content-type helpers
93+
- **Download support**: `sendAsFile('invoice.pdf')` triggers browser download dialog
94+
- Checks `isSent()` to prevent modification after output starts
95+
- **Cookie domain**: If specified, includes subdomains; if omitted, excludes subdomains
96+
97+
#### RequestFactory (`src/Http/RequestFactory.php`)
98+
- Creates Request from PHP superglobals (`$_GET`, `$_POST`, etc.)
99+
- Configurable proxy support (RFC 7239 Forwarded header + X-Forwarded-*)
100+
- URL filters for cleaning malformed URLs
101+
- File upload normalization into FileUpload objects
102+
103+
#### URL Classes
104+
- **`Url`** - Mutable URL builder with setters, supports `appendQuery()` to add parameters
105+
- **`UrlImmutable`** - Immutable URL with wither methods
106+
- `resolve($reference)` - Resolves relative URLs like a browser (v3.3.2+)
107+
- `withoutUserInfo()` - Removes user and password (⚠️ **deprecated**)
108+
- **`UrlScript`** - Request URL with virtual components:
109+
- `baseUrl` - Base URL including domain and path to app root
110+
- `basePath` - Path to application root directory
111+
- `scriptPath` - Path to current script
112+
- `relativePath` - Script name relative to basePath
113+
- `relativeUrl` - Everything after baseUrl (query + fragment)
114+
- `pathInfo` - Rarely used part after script name
115+
- **Static helpers**:
116+
- `Url::isAbsolute($url)` - Checks if URL has scheme (v3.3.2+)
117+
- `Url::removeDotSegments($path)` - Normalizes path by removing `.` and `..` (v3.3.2+)
118+
- All support IDN (via `ext-intl`), canonicalization, query manipulation
119+
120+
#### Session (`src/Http/Session.php` + `SessionSection.php`)
121+
- **Auto-start modes**:
122+
- `smart` - Start only when session data is accessed (default)
123+
- `always` - Start immediately with application
124+
- `never` - Manual start required
125+
- Namespaced sections to prevent naming conflicts
126+
- **SessionSection API**: Use explicit methods instead of magic properties:
127+
- `$section->set('userName', 'john')` - Write variable
128+
- `$section->get('userName')` - Read variable (returns null if missing)
129+
- `$section->remove('userName')` - Delete variable
130+
- `$section->set('flash', $message, '30 seconds')` - Third parameter sets expiration
131+
- Per-section or per-variable expiration
132+
- Custom session handler support
133+
- **Events**: `$onStart`, `$onBeforeWrite` - Callbacks invoked after session starts or before write to disk
134+
- **Session ID management**: `regenerateId()` generates new ID (e.g., after login for security)
135+
136+
#### FileUpload (`src/Http/FileUpload.php`)
137+
- Safe file upload handling
138+
- Content-based MIME detection (requires `ext-fileinfo`)
139+
- Image validation and conversion (supports JPEG, PNG, GIF, WebP, AVIF)
140+
- Sanitized filename generation
141+
- **Filename methods**:
142+
- `getUntrustedName()` - Original browser-provided name (⚠️ never trust!)
143+
- `getSanitizedName()` - Safe ASCII-only name `[a-zA-Z0-9.-]` with correct extension
144+
- `getSuggestedExtension()` - Extension based on MIME type (v3.2.4+)
145+
- `getUntrustedFullPath()` - Full path for directory uploads (PHP 8.1+, ⚠️ never trust!)
146+
147+
#### SSRF Protection Kit (v3.4.0)
148+
149+
Two immutable, framework-optional value objects for guarding server-side URL fetches against SSRF and DNS rebinding.
150+
151+
- **`IPAddress`** (`src/Http/IPAddress.php`) - Immutable IPv4/IPv6 value object
152+
- Construct from string (throws `Nette\InvalidArgumentException` on invalid), or `IPAddress::tryFrom()` / `IPAddress::isValid()`
153+
- Class predicates: `isPublic()`, `isPrivate()` (RFC 1918/4193), `isLoopback()`, `isLinkLocal()` (incl. cloud metadata `169.254.169.254`), `isMulticast()`, `isReserved()`
154+
- Family: `isIPv4()`, `isIPv6()`, `isIPv4Mapped()`, `toIPv4()` (normalizes `::ffff:a.b.c.d`)
155+
- CIDR matching: `isInRange('10.0.0.0/8')` (accepts network/prefix or bare IP as implicit /32 or /128); IPv4-mapped IPv6 is normalized to IPv4 for IPv4 ranges
156+
- **`UrlValidator`** (`src/Http/UrlValidator.php`) - Configurable policy guard
157+
- Constructor policy: `$schemes` (default `['https']`), `$ports` (default `[443]`, `null` = any), `$allowPrivateIps`, `$allowLoopback`, `$allowLinkLocal`, `$allowReserved`, `$allowUserinfo`, `$hostAllowlist`, `$hostBlocklist`
158+
- Host patterns: exact (`example.com`) or wildcard subdomain (`*.example.com`, any depth but NOT apex). Multicast is always rejected
159+
- `allows($url)` - full check incl. DNS: every resolved A/AAAA must pass the IP-range policy
160+
- `allowsWithoutDns($url)` - fast pre-filter, no DNS (e.g. when DNS validation is delegated to the fetch layer)
161+
- `getResolvedIPs($url)` - returns validated IPs (A first, then AAAA) to pin the connection via `CURLOPT_RESOLVE` and defeat DNS rebinding
162+
163+
#### Helpers (`src/Http/Helpers.php`)
164+
- `Helpers::expirationToSeconds()` (v3.4.0) - single consistent expiration parser for the whole library. Numbers are relative seconds; `DateTimeInterface` and textual strings (`'20 minutes'`, `'2024-01-01'`) resolve as absolute times
165+
- `Helpers::parseQualityList()` (v3.4.0) - parses HTTP quality-value lists (`Accept`, `Accept-Language`, …) into a ranked token map; `Request::detectLanguage()` is built on it
166+
- `Helpers::formatDate()` - RFC 7231 HTTP date format
167+
- `Helpers::StrictCookieName` - constant for the strict same-site cookie (`_nss`; old `STRICT_COOKIE_NAME` deprecated)
168+
169+
### Nette DI Integration
170+
171+
Two extensions provide auto-wiring:
172+
173+
1. **HttpExtension** (`src/Bridges/HttpDI/HttpExtension.php`)
174+
- **Registers**: `http.requestFactory`, `http.request`, `http.response`
175+
- **Configuration**: proxy IPs, headers, CSP, X-Frame-Options, cookie defaults
176+
- **CSP with nonce**: Automatically generates nonce for inline scripts
177+
```neon
178+
http:
179+
csp:
180+
script-src: [nonce, strict-dynamic, self]
181+
```
182+
Use in templates: `<script n:nonce>...</script>` - nonce filled automatically
183+
- **Cookie defaults**: `cookiePath`, `cookieDomain: domain` (includes subdomains), `cookieSecure: auto`
184+
- **X-Frame-Options**: `frames: SAMEORIGIN` (default) or `frames: true` to allow all
185+
186+
2. **SessionExtension** (`src/Bridges/HttpDI/SessionExtension.php`)
187+
- **Registers**: `session.session`
188+
- **Configuration**: `autoStart: smart|always|never`, expiration, handler, all PHP `session.*` directives in camelCase
189+
- **Tracy debugger panel**: Enable with `debugger: true` in config
190+
- **Session cookie**: Configure separately with `cookieDomain`, `cookieSamesite: Strict|Lax|None`. `Session::setCookieParameters()` also accepts the `SameSite` enum in PHP code
191+
192+
## Code Conventions
193+
194+
### Strict PHP Standards
195+
196+
Every file must start with:
197+
```php
198+
declare(strict_types=1);
199+
```
200+
201+
### Modern PHP Features
202+
203+
Requires PHP 8.3 (since v3.4.0). Heavily uses modern features:
204+
205+
```php
206+
// Constructor property promotion with readonly
207+
public function __construct(
208+
private readonly UrlScript $url,
209+
private readonly array $post = [],
210+
private readonly string $method = 'GET',
211+
) {
212+
}
213+
214+
// Named arguments + backed enums
215+
$response->setCookie($name, $value, $expire, sameSite: SameSite::Lax);
216+
217+
// First-class callables
218+
Nette\Utils\Callback::invokeSafe(
219+
'session_start',
220+
[['read_and_close' => $this->readAndClose]],
221+
fn(string $message) => throw new Exception($message)
222+
);
223+
```
224+
225+
### Property Documentation with SmartObject
226+
227+
Uses `@property-read` magic properties with Nette's SmartObject trait:
228+
229+
```php
230+
/**
231+
* @property-read UrlScript $url
232+
* @property-read array $query
233+
* @property-read string $method
234+
*/
235+
class Request implements IRequest
236+
{
237+
use Nette\SmartObject;
238+
}
239+
```
240+
241+
### Testing with Nette Tester
242+
243+
Test files use `.phpt` extension and follow this pattern:
244+
245+
```php
246+
<?php
247+
248+
declare(strict_types=1);
249+
250+
use Nette\Http\Url;
251+
use Tester\Assert;
252+
253+
require __DIR__ . '/../bootstrap.php';
254+
255+
test('Url canonicalization removes duplicate slashes', function () {
256+
$url = new Url('http://example.com/path//to/../file.txt');
257+
$url->canonicalize();
258+
Assert::same('http://example.com/path/file.txt', (string) $url);
259+
});
260+
261+
test('Url handles IDN domains', function () {
262+
$url = new Url('https://xn--tst-qla.de/');
263+
$url->canonicalize();
264+
Assert::same('https://täst.de/', (string) $url);
265+
});
266+
```
267+
268+
The `test()` helper is defined in `tests/bootstrap.php`.
269+
270+
## Development Guidelines
271+
272+
### When Adding Features
273+
274+
1. **Read existing code first** - Understand patterns before modifying
275+
2. **Security first** - Consider injection, XSS, CSRF implications
276+
3. **Maintain immutability contracts** - Don't add setters to immutable classes
277+
4. **Test thoroughly** - Add `.phpt` test files in `tests/Http/`
278+
5. **Check Windows compatibility** - Tests run on Windows in CI
279+
280+
### Common Patterns
281+
282+
**Proxy detection** - Use RequestFactory's `setProxy()` for trusted proxy IPs:
283+
```php
284+
$factory->setProxy(['127.0.0.1', '::1']);
285+
```
286+
287+
**URL filtering** - Clean malformed URLs via urlFilters:
288+
```php
289+
// Remove spaces from path
290+
$factory->urlFilters['path']['%20'] = '';
291+
292+
// Remove trailing punctuation
293+
$factory->urlFilters['url']['[.,)]$'] = '';
294+
```
295+
296+
**Cookie security** - Response uses secure defaults:
297+
```php
298+
// httpOnly=true, sameSite=Lax by default
299+
$response->setCookie('name', 'value', '1 hour');
300+
```
301+
302+
**Session sections** - Namespace session data with explicit methods:
303+
```php
304+
$section = $session->getSection('cart');
305+
$section->set('items', []);
306+
$section->setExpiration('20 minutes');
307+
308+
// Per-variable expiration
309+
$section->set('flash', $message, '30 seconds');
310+
311+
// Events
312+
$session->onBeforeWrite[] = function () use ($section) {
313+
$section->set('lastSaved', time());
314+
};
315+
```
316+
317+
## CI/CD Pipeline
318+
319+
GitHub Actions runs:
320+
321+
1. **Tests** (`.github/workflows/tests.yml`):
322+
- Matrix: Ubuntu/Windows/macOS × PHP 8.3-8.5 × php/php-cgi
323+
- Lowest dependencies test
324+
- Code coverage with Coveralls
325+
326+
2. **Static Analysis** (`.github/workflows/static-analysis.yml`):
327+
- PHPStan level 8 (see `phpstan.neon`)
328+
329+
3. **Coding Style** (`.github/workflows/coding-style.yml`):
330+
- Nette Coding Standard (PSR-12 based)
331+
332+
## Architecture Principles
333+
334+
- **Single Responsibility** - Each class has one clear purpose
335+
- **Dependency Injection** - Constructor injection, no service locators
336+
- **Type Safety** - Everything typed (properties, parameters, returns)
337+
- **Fail Fast** - Validation at boundaries, exceptions for errors
338+
- **Framework Optional** - Works standalone or with Nette DI
339+
340+
## Important Notes
341+
342+
- **Browser behavior** - Browsers don't send URL fragments or Origin header for same-origin GET requests
343+
- **Proxy configuration critical** - Required for correct IP detection and HTTPS detection
344+
- **Session auto-start modes**:
345+
- `smart` - Starts only when `$section->get()`/`set()` is called (default)
346+
- `always` - Starts immediately on application bootstrap
347+
- `never` - Must call `$session->start()` manually
348+
- **URL encoding nuances** - Respects PHP's `arg_separator.input` for query parsing
349+
- **FileUpload validation** - Always check `hasFile()` and `isOk()` before processing
350+
- **UrlScript virtual components** - Generated by RequestFactory, understand baseUrl vs basePath distinction
351+
- **CSP nonce in templates** - Use `<script n:nonce>` for automatic nonce insertion with CSP headers

0 commit comments

Comments
 (0)