Search by

noas / framework

rdjohou

The zero-magic, API-first PHP 8.4+ micro-framework built for FrankenPHP, TypeScript, and MCP.

v0.1.0 2026-11-29 00:26 UTC

This package is auto-updated.

Last update: 2026-11-29 00:47:20 UTC


README

⚡ Noas (noas/framework)

The zero-dependency, API-first PHP 8.4+ framework built for FrankenPHP, TypeScript frontends, and AI agents (MCP).

See ARCHITECTURE.md for component ownership, dependency boundaries, and guidance for hexagonal applications.

✨ Key Features

• 0 External Dependencies: Pure native PHP 8.4+ core. • 1 DTO = REST + TypeScript + MCP: Write a readonly PHP DTO once to validate HTTP payloads (#[Body], #[Query]), auto-generate /api/_types.ts for Next.js/Angular, and expose JSON-RPC tools (#[McpTool] on POST /mcp) for Claude & Cursor. • Native SSE Streaming: Stream real-time events using PHP generators (SseStream). • Zero-SDK OpenTelemetry: Native W3C traceparent propagation + OTLP/HTTP export + automatic PDO query tracing. • Cloud-Native & Mesh-Ready: Built-in /healthz probes, APCu rate limiting, and #[AuthUser] injection.

🚀 Quick Start

bash composer create-project noas/skeleton my-api

HTTP values

Noas\Http\Request and Noas\Http\Response are final readonly values. Requests expose method, path, lowercase headers, query, rawBody, and attributes:

use Noas\Http\Request;
use Noas\Http\Response;

$request = Request::fromGlobals();
$authorization = $request->header('Authorization'); // null when absent
$authenticated = $request->withAttribute('auth', ['id' => 7]);
$response = Response::json(['ok' => true], 201)
    ->withHeaders(['X-Request-Id' => 'example']);
$response->send();

Copies do not modify their originals. Header replacement is case-insensitive. Immutability is shallow: use immutable objects for object-valued attributes. The globals factory captures REMOTE_ADDR as attributes['remote_addr'].

Globals capture reads the body incrementally with a default limit of 1 MiB (1,048,576 bytes). Configure a positive byte limit with new Application(maxBodyBytes: 2_097_152) or Request::fromGlobals(2_097_152). Oversized capture returns 413 Problem Details from Application::run() before request middleware runs. This default is a breaking change for larger bodies; also configure limits and timeouts at your ingress. Manually constructed requests are not captured from globals and can use JsonBodyLimitMiddleware.

Response bodies accept string|Noas\Http\SseStream. Stream producers remain lazy until Response::send(), which owns status and headers; SseStream emits events only. A 204 response never emits a body.

Middleware and routing

All native middleware and their interface live in Noas\Middleware. All attributes live in Noas\Attribute, with one class per file and native PSR-4 autoloading (no special classmap). The repeatable UseMiddleware attribute targets controllers and methods. Noas\Kernel\Router stays in the Kernel:

use Noas\Attribute\UseMiddleware;
use Noas\Attribute\Route;
use Noas\Http\Request;
use Noas\Http\Response;
use Noas\Kernel\Application;
use Noas\Kernel\Container;
use Noas\Kernel\Router;
use Noas\Middleware\JsonBodyLimitMiddleware;
use Noas\Middleware\MiddlewareInterface;

final readonly class RequestIdMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        $id = $request->header('x-request-id') ?? bin2hex(random_bytes(8));
        return $next($request->withAttribute('request_id', $id))
            ->withHeaders(['X-Request-Id' => $id]);
    }
}

#[UseMiddleware(JsonBodyLimitMiddleware::class, args: ['maxBytes' => 1024])]
final readonly class ExampleController
{
    #[Route('GET', '/example')]
    public function example(): string
    {
        return 'hello';
    }
}

$app = new Application();
$app->addMiddleware(new RequestIdMiddleware());
$app->registerControllers([ExampleController::class]);
$response = $app->handle(new Request('GET', '/example')); // no output

$router = new Router();
$router->registerControllers([ExampleController::class]);
$response = $router->handle(new Request('GET', '/example'), new Container());

Entry order is global registration order, controller attribute order, then method attribute order; response decoration unwinds in reverse. Middleware can return a Response without calling $next. Exceptions become RFC 9457 Problem Details responses before outer middleware decorates them: HTTP exception codes 400-599 are retained, others map to 500. There is no process() API, old middleware namespace, alias, or compatibility adapter. The shared mapper is Noas\Http\ProblemDetails::fromException(Throwable): Response; native middleware does not depend on Kernel pipeline orchestration.

Controllers can return DTOs, arrays/scalars, Response, or SseStream. Preserve DTO return declarations for TypeScript payload inference. Request attributes flow through middleware; bearer middleware stores claims at attributes['auth'] for #[AuthUser] injection. Bind Noas\Security\TokenVerifierInterface explicitly before using Noas\Middleware\BearerTokenMiddleware. There is no direct Request parameter injection into controllers.

JsonBodyLimitMiddleware rejects bodies over its byte limit with 413. RateLimitMiddleware(maxRequests: 60, windowSeconds: 60) returns rate-limit headers and rejects exhausted buckets with 429 and Retry-After. It uses the captured remote_addr attribute (loopback if absent for manually constructed requests). Forwarded addresses are ignored by default; this is a breaking change for deployments relying on X-Forwarded-For. Configure only trusted proxy addresses or CIDR ranges, for example new RateLimitMiddleware(trustedProxies: ['10.0.0.0/8', '2001:db8:ffff::/48']). The immediate peer must be trusted, and the chain is evaluated from nearest to farthest. Missing, malformed or entirely trusted chains fall back to the immediate peer. Configure ingress to replace untrusted forwarded headers and prevent direct access to the application. Rate counters use APCu when enabled, or locked temporary files otherwise; request identities are never retained in middleware instances. Neither backend provides a shared limit across pods by default: enforce a global limit at the ingress or service mesh when needed.

HTTP errors (Problem Details)

Exception-backed HTTP errors use RFC 9457, which replaces RFC 7807, with Content-Type: application/problem+json:

{
  "type": "about:blank",
  "title": "Unprocessable Content",
  "status": 422,
  "detail": "Validation failed.",
  "errors": {
    "email": ["Field 'email' must be a valid email address."]
  }
}

The body status matches the HTTP status. Titles use English HTTP reason phrases, or Client Error/Server Error for unrecognized codes. Client-error details expose the exception message, which must be suitable for public consumption. Server errors (5xx) instead use a generic detail and log the original exception through PHP's native error_log; no PHP class name or trace is sent to the client. The optional instance member is not generated.

Noas\Validation\ValidationException carries readonly structured field errors. They appear in the HTTP errors extension, not as JSON embedded in a message. CORS, bearer challenges, and rate-limit headers remain attached to error responses. Health status representations retain their existing JSON format.

This replaces the previous error/exception-class type body and the ErrorResponse class outright, without an alias. Clients must adopt the new media type and fields. MCP protocol errors retain JSON-RPC, not Problem Details.

CORS

Application installs one Noas\Middleware\CorsMiddleware first. Replace its configuration through the constructor, not by adding a second CORS middleware:

use Noas\Kernel\Application;
use Noas\Middleware\CorsMiddleware;

$app = new Application(new CorsMiddleware(
    allowedOrigins: ['https://app.example'],
    allowedMethods: ['GET', 'POST'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    allowCredentials: true,
    maxAge: 600,
));

Defaults are wildcard origins, GET/POST/PUT/PATCH/DELETE/OPTIONS, Content-Type/Authorization/X-Request-Id/traceparent, credentials disabled, and maxAge 0. Credentialed wildcard origins, negative max age, and invalid list values are rejected. Origins match exactly. Explicit-origin policies vary all responses by Origin, including absent/refused origins, preserving other Vary tokens and Vary: *. Refused origins receive no allow headers.

Every OPTIONS request returns an empty 204 before later globals, route matching, or controller middleware. Advertised methods/headers are configured values, never reflected untrusted permissions. Other requests, including errors and the health, TypeScript, and MCP endpoints, pass through global middleware.

Worker lifecycle and contracts

Application::handle(Request): Response performs no output and starts no trace. Application::run(): void captures the current request once, handles it, and sends the response. Call run() for each worker iteration; request data stays local even though the application and container are reused.

Tracing surrounds handling and emission, including lazy SSE production, and is reset in finally even if capture, emission, or export fails. Capture failures produce explicit error responses outside the request pipeline, without middleware headers because no Request exists yet. A stream failure after headers are sent propagates without changing the committed HTTP status or appending JSON. Hosts must log propagated failures and decide worker recovery.

GET /healthz preserves healthy 200 and unhealthy 503 JSON responses. GET /api/_types.ts returns generated TypeScript text. POST /mcp wraps existing JSON-RPC serialization without double encoding. DTO discovery remains shared between REST, TypeScript, and MCP; controller/method HTTP middleware does not execute inside MCP tool calls.

MCP authentication and authorization

By default, MCP denies access unless the current request has an authenticated auth attribute and an application-owned ToolAuthorizationInterface is configured. This is a breaking change for existing MCP consumers and direct McpServer::handleJsonRpc() callers. Authenticate requests through trusted middleware and pass the identity and policy explicitly to direct callers. Never derive the identity directly from an unverified client-supplied value.

The policy separately controls discovery and invocation. tools/list exposes only discoverable tools; tools/call checks both permissions with the actual arguments. Only boolean decisions are accepted; missing policies, invalid decisions and policy errors fail closed. Policy instances must not retain request identities. For example, an application can supply its own verifier:

use Noas\Kernel\Application;
use Noas\Mcp\ToolAuthorizationInterface;
use Noas\Middleware\BearerTokenMiddleware;
use Noas\Security\TokenVerifierInterface;

final readonly class ExampleToolPolicy implements ToolAuthorizationInterface
{
    public function canDiscover(array|object $identity, string $tool): bool
    {
        return is_array($identity)
            && ($identity['role'] ?? null) === 'operator'
            && $tool === 'create_item';
    }

    public function canInvoke(array|object $identity, string $tool, array $arguments): bool
    {
        return $this->canDiscover($identity, $tool);
    }
}

function createApplication(TokenVerifierInterface $verifier): Application
{
    $app = new Application(mcpAuthorization: new ExampleToolPolicy());
    $app->addMiddleware(new BearerTokenMiddleware($verifier));
    return $app;
}

This example applies bearer authentication to all HTTP endpoints. Scope the authentication middleware to /mcp if public health checks are required. Other authentication mechanisms can attach their verified identity to auth; the framework does not require JWT. Applications must implement their own tool- and argument-level authorization.

Anonymous access is disabled unless a separate anonymous policy is configured. For example, an application that registers a read_public_catalog tool can opt in to exposing only that tool:

use Noas\Kernel\Application;
use Noas\Mcp\AnonymousIdentity;
use Noas\Mcp\ToolAuthorizationInterface;

final readonly class PublicToolPolicy implements ToolAuthorizationInterface
{
    public function canDiscover(array|object $identity, string $tool): bool
    {
        return $identity instanceof AnonymousIdentity && $tool === 'read_public_catalog';
    }

    public function canInvoke(array|object $identity, string $tool, array $arguments): bool
    {
        return $this->canDiscover($identity, $tool);
    }
}

$app = new Application(mcpAnonymousAuthorization: new PublicToolPolicy());

Authenticated requests use only mcpAuthorization; anonymous requests use only mcpAnonymousAuthorization. A missing policy never falls back to the other mode. Invalid auth attributes are rejected rather than downgraded. Direct McpServer::handleJsonRpc() callers must explicitly supply new AnonymousIdentity() and the intended anonymous policy.

Anonymous access does not make tools read-only or safe by itself and does not enable rate limiting. Restrict exposed tools and arguments, configure rate limits and ingress protections, and reject invalid credentials in trusted authentication middleware. The framework cannot detect every credential format. The bearer middleware shown above rejects missing tokens, so applications that allow both modes need middleware that permits absent credentials but rejects invalid ones.

REST and MCP both invoke Noas\Validation\DtoValidator before passing an input DTO to the controller/tool. Email and Length failures retain the same validation details: HTTP 422 Problem Details for REST, or a JSON-RPC error with code 422, message Validation failed., and structured error.data.errors for MCP. MCP protocol replies retain HTTP 200 and application/json; HTTP boundary failures, such as request-capture errors, use Problem Details. Valid tool results and generated DTO fields remain unchanged. TypeScript types and current MCP input schemas are not complete runtime validators and do not export Email/Length constraints.

The skeleton and official JWT/OpenAPI extensions use Noas\Attribute, Noas\Middleware, and Noas\Security\TokenVerifierInterface. Router remains Noas\Kernel\Router; obsolete namespaces have no aliases. The TypeScript client handles Problem Details through NoasApiError.problem and preserves access to the actual HTTP status and policy headers.

Verification

Run composer ci with PHP 8.4+ and PHPStan available on PATH. Tests use native PHP assertions in tests/Unit/ and tests/Integration/; run a focused case with php -d zend.assertions=1 -d assert.exception=1 tests/run.php "name fragment". The lint script requires Unix find/xargs (on Windows, put Git's usr\bin on PATH before the Windows tools). No runtime Composer packages are needed.

Production release checklist

This change is not evidence that a release is production-ready. Record the candidate version and commit, the owner and result of each check, and links to the evidence. Every missing or failing item below blocks production approval:

  • Passing lint, PHPStan, native tests and optimized PSR-4 autoload checks for PHP 8.4, 8.5 and 8.6 in CI. A configured matrix alone is not evidence.
  • A PHP-capable security scan run locally without exporting source or findings, with reviewed rules and the qualified new-finding gate. CodeQL's Actions analysis and PHPStan are not PHP security-scan coverage. The PHP SAST evaluation and gate are not yet established.
  • An independent manual security review of the candidate and resolution or explicitly approved disposition of its findings. No completed independent review is currently recorded.
  • Validation of the actual FrankenPHP persistent worker, including sequential authenticated and rejected requests, state cleanup and tracing. Native tests alone do not prove worker-mode behavior; real-worker evidence is not recorded.
  • Agreed throughput, concurrency, duration and resource limits for the target deployment, plus recorded load-test results meeting those limits. Targets and results are not yet established.
  • Compatibility and release evidence from the dependent repositories, including a scan of the actual skeleton image built with this exact locked candidate. Until those independent follow-ups are complete, production approval is blocked.

The MCP default-deny policy, bounded body capture and trusted-proxy defaults are breaking changes. Before publishing, determine the appropriate version from the actual published compatibility baseline, migrate consumers using the guidance above and verify them against the candidate. A rollback must restore a matching previous framework and consumers, not weaken the new security defaults.

Separately owned repository follow-ups

Each project owns its own GitHub repository, OpenSpec root and appropriate workflows. These follow-ups are separate changes in those repositories; this framework change does not implement or complete them.

Repository Owner's follow-up
Framework Configure and verify its own OpenSpec and workflows; complete the release checks above for the identified candidate.
Skeleton Configure its own OpenSpec and workflows; migrate and test against the exact locked framework candidate and scan the deployed FrankenPHP image. The skeleton remains a demonstration, not production-ready authentication.
Client Configure its own OpenSpec and workflows; verify generated contracts and compatibility with the same framework candidate.
JWT Configure its own OpenSpec and workflows; verify authentication integration and compatibility with the same framework candidate.
OpenAPI Configure its own OpenSpec and workflows; verify generated API contracts and compatibility with the same framework candidate.

Skeleton CI must build and scan the actual deployable image containing the exact locked framework candidate, recording both identities and the scan result. High and critical image findings, including vulnerabilities with no available fix, block release unless an exception is documented and approved by an accountable owner. A scan of another image or framework version is not evidence for this candidate.