Repository navigation
Taphra 1.0.0
A PHP framework for the agent era. Website and guides: https://taphra.dev · Start here: https://taphra.dev/docs/getting-started/
The first public release.
Requirements: PHP 8.2, 8.3 or 8.4 (all three tested in CI) with the curl, json, mbstring, pdo and sodium extensions. Install the framework with composer require taphra/taphra, or start an app with composer create-project taphra/skeleton my-app (also taphra/api-starter, taphra/ai-chat and taphra/mcp-server).
Added
- One installable package,
taphra/taphra, that includes seven libraries also published on their own:taphra/db,taphra/validator,taphra/container,taphra/crypt,taphra/l10n,taphra/aiandtaphra/billing. - Web layer: YAML routes with named parameters, named routes and route groups with PSR-15 middleware; controllers with views, layouts and elements; HTML and form helpers; Server-Sent Events and HTMX helpers; a
RestControllerand aCrudControllerfor JSON APIs, API resources and OpenAPI output (php taphra route:openapi). - Requests and validation: typed input accessors, a string-rule validator and form requests.
- Database: DataStores (one class per table) with a query builder, casts, relations and eager loading, scopes, global filters, hooks, observers, timestamps, soft deletes and pagination; SqlQuery for joins, CTEs, set operations, window functions, upserts and
RETURNING; a schema builder and migrations; seeders and factories. - Authentication: session and JWT drivers, remember-me cookies, password hashing, password reset and email verification tokens, TOTP two-factor codes with backup codes, policies.
- Application services: queues (Redis, database, Beanstalkd) with
queue:work, cache drivers and locks, events, a scheduler run from one cron entry, email over PHPMailer, localisation with ICU plural rules, billing with a Stripe provider and a null provider for tests. - AI: Anthropic, OpenAI and Ollama providers behind one interface. OpenAI uses the Responses API for reasoning models and Chat Completions otherwise, which also serves OpenAI-compatible servers. Token streaming, structured output (Ollama
format, OpenAI strict mode as an option, Anthropicoutput_config), a provider-neutral agent loop with tool use, thinking blocks kept across turns, server tools, usage figures with cache tokens, conversations, prompt templates,FallbackProviderforcomplete()andstream(),CachedProvider, andAiConfig::snapshot()/restore(). - MCP: a server that negotiates protocol versions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05; tools, resources and prompts declared with PHP attributes; a stdio transport (
php taphra mcp:serve) and a Streamable HTTP transport. - Operations:
php taphra optimize(compiled config and routes, an opcache preload script), FrankenPHP worker mode, request IDs in every log line, an opt-in request log withphp taphra debug:request, andphp taphra tinker. Taphra\Framework, the application singleton, withFramework::mode()andFramework::modeFromEnvironment(); the global classTaphrais an alias of it.Taphra\Helpers, the namespaced form of the template helpers (Helpers::e(),Helpers::url()and the others). Each global helper function is defined only when no function of that name exists yet, so an app or a library can define its owne(),dump()ordd().Taphra\TaphraExceptionInterface, implemented by every exception class of Taphra and its packages, so onecatchhandles any framework error.- The AI app builder,
php taphra ai:build,ai:fixandai:rollback, as a preview feature: it works, and its behaviour may still change in minor releases. It asks before every file write and before every command outside an exact allow-list, never runs a shell, and keeps a receipt so a session can be rolled back.
Changed
For apps built on a pre-release copy of Taphra:
- The logging helpers are
tphr_log(),tphr_dbg(),tphr_warning(),tphr_notice()andtphr_err(). The session keys (_tphr_errors,_tphr_old,_tphr_user) and the remember-me cookie (_tphr_remember) use thetphr_prefix, so signed-in users sign in again once after the upgrade. The widget folder constant isTPHR_WIDGET_PATH, client components register onwindow.__TAPHRA_COMPONENTS__, and the request log isapp/tmp/Log/requests.log. - The skeleton turns on
routing.strict: a POST, PUT, PATCH or DELETE request needs a route that declares that method, and a GET never reaches an action that a POST route binds.make:crudand the other generators print routes in method sections. - The action cache serves anonymous GET and HEAD requests only, and its key includes the query string.
- Error pages are chosen per status (the app's
error<status>view, such aserror403orerror429, then a genericerrorview), and production JSON errors carry the status's own reason phrase. - An
.envfile at the app root is loaded at boot (real environment variables win), andapp.keyfalls back toAPP_SECRET_KEY. - With an app key set, queued email jobs carry a signature; jobs queued by a pre-release copy are refused. Queued email is plain data rebuilt by the worker.
- Queue payloads that are not strings are JSON-encoded on push and decoded on pull.
route:openapi --versionis now--api-version.- An unclosed quote in
.envstops the boot with an error that names the line. - Database calls that used to be accepted now throw or behave more strictly: a string under an integer key in a condition array throws, an array id must name exactly the primary key columns, and with
$fillableor$guardeddeclared a primary key insave($data)that is not fillable is dropped, so the call inserts. - The suggested JWT library is
firebase/php-jwt^6.11 or ^7.2. - AI structured output: the answer is checked against the whole JSON Schema (before, only the top-level required fields). Anthropic models from 4.1 on use
output_formatby default instead of a forced tool, and thetools-2024-04-04beta header is no longer sent (structured_output: toolkeeps the forced tool). OpenAI reasoning models go to the Responses API (api: chatkeeps Chat Completions).AiStructuredOutputExceptioncarries the provider's response and usage (response(),usage()), so a billed call whose answer fails the check can still be counted. - AI providers make their HTTP calls through
Taphra\Ai\Http\CurlTransport; replace it withwithTransport()(for exampleFakeTransportin tests) instead of overriding the providers' cURL code.
Removed
- The
php taphra launchandphp taphra utilscommands. Themake:*generators,cache:clearandroute:listcover whatutilsdid.
Security
These defaults apply from 1.0.0. If you are moving an app from a pre-release copy of Taphra, check each one; Upgrading says what to change.
- An unset or unknown
APP_ENVmeans production. The Whoops debug page is only used in development. FormRequest::validated()never returns input that failed its rules: it throwsValidationException(HTTP 422). A newstringrule rejects JSON numbers, booleans and lists where text is expected; the starters use it for passwords and other text fields.- JWTs are refused before their
nbf(not before) time. - Query-result cache entries are keyed by the database they came from (connection name, driver, host, port and database, never credentials) and by DataStore class, so two databases sharing a cache never see each other's rows.
- TOTP codes and billing webhook event ids are claimed with an atomic cache add (Redis SET NX, Memcache add, APCu add, an exclusive file lock), so two simultaneous requests cannot both use one code or run one event twice. A webhook whose id cannot be recorded gets a 500 so the provider retries. A failed handler releases its webhook claim with an atomic compare-and-delete, so it never removes a newer delivery's claim, and verifications of one TOTP secret run one at a time, so the last accepted step never moves backwards.
Auth::hashPassword()uses Argon2id when PHP supports it, otherwise bcrypt, and refuses passwords bcrypt would truncate (over 72 bytes) or that contain a NUL byte.- The cache reads values back with an allow list of classes (DataStore rows and collections,
DateTime,DateTimeImmutable), never with unrestrictedunserialize(). - The AI builder asks before running a
make:*generator, like any other file write. - Only the public methods an app's controllers declare are URL actions. The base class helpers (
sse(),redirect(),csrf(), thehtmx*()helpers and the others) are protected or otherwise not reachable from a URL.sse()takes a Generator or a Closure. - A request with the wrong HTTP method for a declared route gets 405 with an
Allowheader. - CSRF tokens are checked on every request that is not GET, HEAD or OPTIONS, and the skeleton turns the check on for its controllers.
- Session cookies are HttpOnly, SameSite=Lax and Secure over HTTPS, and sessions use strict mode.
X-Forwarded-ForandX-Forwarded-Protoare trusted only from the addresses inapp.trusted_proxies.url()builds absolute links frombase_urlin production, never from theHostheader.- Route group middleware runs whether a route is reached by its declared path or by its controller/action URL.
- Database values are always bound as parameters, and identifiers and operators are checked; raw SQL goes only through the
*Raw()methods.$fillableand$guardedare respected.findOrFail()throwsTaphra\Db\RecordNotFoundException, which the framework answers with 404. - Email bodies use
{{ name }}placeholders, escaped in HTML bodies, instead of running as PHP. - The HTML helpers escape attributes, option labels and anchor text (
SafeStringopts out), ande()does not escape a value twice. - The validator throws on an unknown rule,
minandmaxmeasure string length for strings, andurlaccepts only http, https and ftp. Cryptneeds 32-byte keys; passphrases have their own API. JWT secrets must be at least 32 bytes. TOTP verification fails closed when the cache is unavailable.- Queue workers only run classes that implement
Taphra\Queue\JobInterface. - The MCP HTTP transport refuses every request until a token is set or
authorizeMcp()is overridden, checks theOriginheader and requires JSON. - Worker mode resets per-request state between requests (
RequestState::reset()). - Production logs
noticeand above by default (app.logging.level), andlogging.method: nulldiscards log entries. JwtMiddlewareandJwtAuthaccept access tokens only (token_use: access). Tokens withouttoken_usestill work unless_type,typortypemarks them as refresh tokens, so refresh tokens from earliermake:authcontrollers ("_type": "refresh") are refused.- The AI builder no longer runs git (run it yourself), blocks wrappers that run another program (flock, tmux, screen, setarch and similar), more interpreters, and Windows scripts and shells (names are matched without
.exe), and refuses commands and paths that name.env,.gitor Windows short names such asGIT~1. With--dontaskforpermissionsonly Taphra commands and the file tools run.ai:build --continuekeeps asking before every command once earlier sessions wrote files, and approval prompts show every invisible Unicode character as a visible escape. - The opt-in request log writes cookies,
Authorization, and headers, query parameters and body fields named like a token, secret, key, password, pass, pw, otp, code, jwt, pin, session id or CSRF field as[redacted], redacts bodies it cannot parse and token-like path segments, and does not rewrite existing entries. - The action cache stores the status and the headers that say how to read the body (
Content-Type, CSP,X-Content-Type-Options,HX-*) and sends them again on a hit;Accept,Accept-Languageand the htmx headers are part of the key. $guardedmatches column names in any case, and keys that are not columns are dropped.firstOrCreate()andupdateOrCreate()filter their data through$fillableand$guarded.- Login and message limits in the starters and in
make:authuseRateLimiter::attempt(), which cannot be raced.Auth::verifyPassword()accepts null and checks a dummy hash, so login timing does not reveal which accounts exist. - The generated
AppRestControllerreadsJwtMiddleware::payload(), never request input. - Worker mode forgets the previous session id between requests.
- Queued email needs an app key and attaches only files from
app.email.attachments_path(defaultapp/tmp/attachments). - JSON error bodies show the exception message in development only.
- MCP tokens must be at least 32 bytes; the mcp-server starter writes one at
create-projectand exposes one endpoint. All four starters turn onrouting.strict. make:dockerfilepublishes the app on 127.0.0.1 only, publishes no database or Redis port, and keeps a randomDB_PASSWORDin.env.
Known limitations
- MCP: the stateless 2026-07-28 protocol revision is not implemented (clients that speak both fall back to
initialize). The server answers requests only: no sampling, elicitation, resource subscriptions or list-changed notifications. The HTTP transport answers with JSON (no server-initiated SSE stream) and keeps sessions in files on one server. - Tool arguments are not checked against the tool's input schema, in the agent loop and in MCP
tools/call. Validate them in the tool. AI::stream()yields text only, and a streamed request is not retried on HTTP 429.- Queues have no delayed dispatch, a job that was running when its worker died is not retried, and
queue:failedonly prints a reminder. - The scheduler has no overlap protection.
- On the default entry (
app/Static/index.php), route middleware can stop a request and add headers, but cannot change the response body or status, and a JSON request body is not part ofRequest::input(). Routes are the same in every environment. - SQL Server support is generated SQL covered by unit tests of that SQL; it is not tested against a running server.
MongodbConnectionis experimental and not tested against a running server. DataStores on MongoDB are not supported: a condition that cannot be turned into a MongoDB filter is refused.- There is no WebSocket server. A Server-Sent Events stream holds a PHP worker for as long as it is open.
- The skeleton loads its own
*.class.phpfiles through a Composer classmap, so a class file you add with that suffix needscomposer dump-autoload. Files named<Class>.php, which themake:*commands write, load at once.