Skip to content

Commit b23ef73

Browse files
committed
added CLAUDE.md
1 parent de5988d commit b23ef73

2 files changed

Lines changed: 328 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: 327 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,327 @@
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+
- **Warning**: Browsers don't send URL fragments to the server (`$url->getFragment()` returns empty string)
84+
85+
#### Response (`src/Http/Response.php`)
86+
- Mutable HTTP response management
87+
- Header manipulation (set/add/delete)
88+
- 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**
89+
- **CHIPS / partitioned cookies**: `setCookie()` has a `bool $partitioned = false` parameter; setting it (or `SameSite::None`) forces the `Secure` attribute
90+
- Redirect, cache control, content-type helpers
91+
- **Download support**: `sendAsFile('invoice.pdf')` triggers browser download dialog
92+
- Checks `isSent()` to prevent modification after output starts
93+
- **Cookie domain**: If specified, includes subdomains; if omitted, excludes subdomains
94+
95+
#### RequestFactory (`src/Http/RequestFactory.php`)
96+
- Creates Request from PHP superglobals (`$_GET`, `$_POST`, etc.)
97+
- Configurable proxy support (RFC 7239 Forwarded header + X-Forwarded-*)
98+
- URL filters for cleaning malformed URLs
99+
- File upload normalization into FileUpload objects
100+
101+
#### URL Classes
102+
- **`Url`** - Mutable URL builder with setters, supports `appendQuery()` to add parameters
103+
- **`UrlImmutable`** - Immutable URL with wither methods
104+
- `resolve($reference)` - Resolves relative URLs like a browser (v3.3.2+)
105+
- `withoutUserInfo()` - Removes user and password (⚠️ **deprecated**)
106+
- **`UrlScript`** - Request URL with virtual components:
107+
- `baseUrl` - Base URL including domain and path to app root
108+
- `basePath` - Path to application root directory
109+
- `scriptPath` - Path to current script
110+
- `relativePath` - Script name relative to basePath
111+
- `relativeUrl` - Everything after baseUrl (query + fragment)
112+
- `pathInfo` - Rarely used part after script name
113+
- **Static helpers**:
114+
- `Url::isAbsolute($url)` - Checks if URL has scheme (v3.3.2+)
115+
- `Url::removeDotSegments($path)` - Normalizes path by removing `.` and `..` (v3.3.2+)
116+
- All support IDN (via `ext-intl`), canonicalization, query manipulation
117+
118+
#### Session (`src/Http/Session.php` + `SessionSection.php`)
119+
- **Auto-start modes**:
120+
- `smart` - Start only when session data is accessed (default)
121+
- `always` - Start immediately with application
122+
- `never` - Manual start required
123+
- Namespaced sections to prevent naming conflicts
124+
- **SessionSection API**: Use explicit methods instead of magic properties:
125+
- `$section->set('userName', 'john')` - Write variable
126+
- `$section->get('userName')` - Read variable (returns null if missing)
127+
- `$section->remove('userName')` - Delete variable
128+
- `$section->set('flash', $message, '30 seconds')` - Third parameter sets expiration
129+
- Per-section or per-variable expiration
130+
- Custom session handler support
131+
- **Events**: `$onStart`, `$onBeforeWrite` - Callbacks invoked after session starts or before write to disk
132+
- **Session ID management**: `regenerateId()` generates new ID (e.g., after login for security)
133+
134+
#### FileUpload (`src/Http/FileUpload.php`)
135+
- Safe file upload handling
136+
- Content-based MIME detection (requires `ext-fileinfo`)
137+
- Image validation and conversion (supports JPEG, PNG, GIF, WebP, AVIF)
138+
- Sanitized filename generation
139+
- **Filename methods**:
140+
- `getUntrustedName()` - Original browser-provided name (⚠️ never trust!)
141+
- `getSanitizedName()` - Safe ASCII-only name `[a-zA-Z0-9.-]` with correct extension
142+
- `getSuggestedExtension()` - Extension based on MIME type (v3.2.4+)
143+
- `getUntrustedFullPath()` - Full path for directory uploads (PHP 8.1+, ⚠️ never trust!)
144+
145+
### Nette DI Integration
146+
147+
Two extensions provide auto-wiring:
148+
149+
1. **HttpExtension** (`src/Bridges/HttpDI/HttpExtension.php`)
150+
- **Registers**: `http.requestFactory`, `http.request`, `http.response`
151+
- **Configuration**: proxy IPs, headers, CSP, X-Frame-Options, cookie defaults
152+
- **CSP with nonce**: Automatically generates nonce for inline scripts
153+
```neon
154+
http:
155+
csp:
156+
script-src: [nonce, strict-dynamic, self]
157+
```
158+
Use in templates: `<script n:nonce>...</script>` - nonce filled automatically
159+
- **Cookie defaults**: `cookiePath`, `cookieDomain: domain` (includes subdomains), `cookieSecure: auto`
160+
- **X-Frame-Options**: `frames: SAMEORIGIN` (default) or `frames: true` to allow all
161+
162+
2. **SessionExtension** (`src/Bridges/HttpDI/SessionExtension.php`)
163+
- **Registers**: `session.session`
164+
- **Configuration**: `autoStart: smart|always|never`, expiration, handler, all PHP `session.*` directives in camelCase
165+
- **Tracy debugger panel**: Enable with `debugger: true` in config
166+
- **Session cookie**: Configure separately with `cookieDomain`, `cookieSamesite: Strict|Lax|None`. `Session::setCookieParameters()` also accepts the `SameSite` enum in PHP code
167+
168+
## Code Conventions
169+
170+
### Strict PHP Standards
171+
172+
Every file must start with:
173+
```php
174+
declare(strict_types=1);
175+
```
176+
177+
### Modern PHP Features
178+
179+
Heavily uses PHP 8.1+ features:
180+
181+
```php
182+
// Constructor property promotion with readonly
183+
public function __construct(
184+
private readonly UrlScript $url,
185+
private readonly array $post = [],
186+
private readonly string $method = 'GET',
187+
) {
188+
}
189+
190+
// Named arguments + backed enums
191+
$response->setCookie($name, $value, $expire, sameSite: SameSite::Lax);
192+
193+
// First-class callables
194+
Nette\Utils\Callback::invokeSafe(
195+
'session_start',
196+
[['read_and_close' => $this->readAndClose]],
197+
fn(string $message) => throw new Exception($message)
198+
);
199+
```
200+
201+
### Property Documentation with SmartObject
202+
203+
Uses `@property-read` magic properties with Nette's SmartObject trait:
204+
205+
```php
206+
/**
207+
* @property-read UrlScript $url
208+
* @property-read array $query
209+
* @property-read string $method
210+
*/
211+
class Request implements IRequest
212+
{
213+
use Nette\SmartObject;
214+
}
215+
```
216+
217+
### Testing with Nette Tester
218+
219+
Test files use `.phpt` extension and follow this pattern:
220+
221+
```php
222+
<?php
223+
224+
declare(strict_types=1);
225+
226+
use Nette\Http\Url;
227+
use Tester\Assert;
228+
229+
require __DIR__ . '/../bootstrap.php';
230+
231+
test('Url canonicalization removes duplicate slashes', function () {
232+
$url = new Url('http://example.com/path//to/../file.txt');
233+
$url->canonicalize();
234+
Assert::same('http://example.com/path/file.txt', (string) $url);
235+
});
236+
237+
test('Url handles IDN domains', function () {
238+
$url = new Url('https://xn--tst-qla.de/');
239+
$url->canonicalize();
240+
Assert::same('https://täst.de/', (string) $url);
241+
});
242+
```
243+
244+
The `test()` helper is defined in `tests/bootstrap.php`.
245+
246+
## Development Guidelines
247+
248+
### When Adding Features
249+
250+
1. **Read existing code first** - Understand patterns before modifying
251+
2. **Security first** - Consider injection, XSS, CSRF implications
252+
3. **Maintain immutability contracts** - Don't add setters to immutable classes
253+
4. **Test thoroughly** - Add `.phpt` test files in `tests/Http/`
254+
5. **Check Windows compatibility** - Tests run on Windows in CI
255+
256+
### Common Patterns
257+
258+
**Proxy detection** - Use RequestFactory's `setProxy()` for trusted proxy IPs:
259+
```php
260+
$factory->setProxy(['127.0.0.1', '::1']);
261+
```
262+
263+
**URL filtering** - Clean malformed URLs via urlFilters:
264+
```php
265+
// Remove spaces from path
266+
$factory->urlFilters['path']['%20'] = '';
267+
268+
// Remove trailing punctuation
269+
$factory->urlFilters['url']['[.,)]$'] = '';
270+
```
271+
272+
**Cookie security** - Response uses secure defaults:
273+
```php
274+
// httpOnly=true, sameSite=Lax by default
275+
$response->setCookie('name', 'value', '1 hour');
276+
```
277+
278+
**Session sections** - Namespace session data with explicit methods:
279+
```php
280+
$section = $session->getSection('cart');
281+
$section->set('items', []);
282+
$section->setExpiration('20 minutes');
283+
284+
// Per-variable expiration
285+
$section->set('flash', $message, '30 seconds');
286+
287+
// Events
288+
$session->onBeforeWrite[] = function () use ($section) {
289+
$section->set('lastSaved', time());
290+
};
291+
```
292+
293+
## CI/CD Pipeline
294+
295+
GitHub Actions runs:
296+
297+
1. **Tests** (`.github/workflows/tests.yml`):
298+
- Matrix: Ubuntu/Windows/macOS × PHP 8.3-8.5 × php/php-cgi
299+
- Lowest dependencies test
300+
- Code coverage with Coveralls
301+
302+
2. **Static Analysis** (`.github/workflows/static-analysis.yml`):
303+
- PHPStan level 8 (see `phpstan.neon`)
304+
305+
3. **Coding Style** (`.github/workflows/coding-style.yml`):
306+
- Nette Coding Standard (PSR-12 based)
307+
308+
## Architecture Principles
309+
310+
- **Single Responsibility** - Each class has one clear purpose
311+
- **Dependency Injection** - Constructor injection, no service locators
312+
- **Type Safety** - Everything typed (properties, parameters, returns)
313+
- **Fail Fast** - Validation at boundaries, exceptions for errors
314+
- **Framework Optional** - Works standalone or with Nette DI
315+
316+
## Important Notes
317+
318+
- **Browser behavior** - Browsers don't send URL fragments or Origin header for same-origin GET requests
319+
- **Proxy configuration critical** - Required for correct IP detection and HTTPS detection
320+
- **Session auto-start modes**:
321+
- `smart` - Starts only when `$section->get()`/`set()` is called (default)
322+
- `always` - Starts immediately on application bootstrap
323+
- `never` - Must call `$session->start()` manually
324+
- **URL encoding nuances** - Respects PHP's `arg_separator.input` for query parsing
325+
- **FileUpload validation** - Always check `hasFile()` and `isOk()` before processing
326+
- **UrlScript virtual components** - Generated by RequestFactory, understand baseUrl vs basePath distinction
327+
- **CSP nonce in templates** - Use `<script n:nonce>` for automatic nonce insertion with CSP headers

0 commit comments

Comments
 (0)