gisila 0.4.1
gisila: ^0.4.1 copied to clipboard
A Shelf-based web framework with annotation-driven routing, declarative permission/role checks, pluggable middleware, configurable structured logging, and a small build_runner code generator.
Changelog #
0.4.1 — 2026-10-30 — static files, API keys, pagination, SSE and WebSockets #
0.4.0 was tagged but never published; this release includes it (see below) along with the following.
- Server-sent events:
sseResponse(stream)withSseEvent(multi-line data,event,id,retry, comments,SseEvent.json), unbuffered output, keep-alive comments and cancellation on disconnect;lastEventId(request)for resuming. - WebSockets: upgrades via
shelf_web_socketinside a guarded route now work through the whole pipeline. The error mapper, access log, metrics and DB session let shelf'sHijackExceptionthrough (it used to become a logged 500); the upgrade is logged and counted as101.HijackExceptionis exported. - Fix:
logResponseBodyno longer reads bodies of unknown length (event streams, streamed files), which hung such responses. - Pagination helpers:
PageParams(validated, clampedlimit/offset/cursor; bad values are 400s),Cursor.encode/decodefor keyset pagination (malformed cursors are 400invalid_cursor), andPage<T>, which renders{"items": [...], "page": {...}}withhas_more. ApiKeyAuthenticator: keys inX-API-Key(orheader:/keyFromRequest:), looked up by SHA-256 hash so only hashes are stored; unknown keys are 401invalid_api_key.generate(prefix:)makes 256-bit keys,hash(key)the value to store.CompositeAuthenticator([...]): first principal wins; an authenticator that throws ends the search.app.serveStatic(prefix, directory)serves files (controllers still win; missing files fall through to the JSON 404) with weak ETags,Last-Modified,304s,maxAge/immutablecache lifetimes, and an optional single-page-app fallback toindex.htmlfor page routes. Never serves outside the directory (traversal, encoded slashes, symlinks out), directory listings or dotfiles.staticFilesHandleris the handler on its own. New direct dependency:path.
0.4.0 — 2026-10-30 — JWT auth, test client, metrics, security headers #
Behaviour change: responses now carry security headers by default
(Strict-Transport-Security, X-Content-Type-Options,
X-Frame-Options: DENY, Referrer-Policy, and a CSP on non-HTML
responses). Set AppConfig(securityHeaders: null) to keep the 0.3.0
behaviour. Everything else is additive.
- Metrics:
AppConfig.metricsrecordshttp_server_requests_total,http_server_request_duration_secondsandhttp_server_requests_in_flight(labelled by route template, not raw path) and serves them in the Prometheus format at/metrics, by default only to direct loopback connections without forwarding headers;bearerTokenorallowopen it up.app.metricstakes your own counters, gauges and histograms.MetricsHubmerges the numbers of every isolate serving one port. start(shared: true)lets several isolates serve one port.AppConfig.compression(off by default): gzip for clients that accept it, for compressible MIME types (never SSE) of at leastminBytes; streams are compressed as written; addsVary: Accept-Encoding;shouldCompresscan veto (BREACH).Content-Encoding: identityon a response opts it out.AppConfig.etags(off by default): hashesGET/HEAD200 bodies up tomaxBytesinto anETagand answersIf-None-Matchwith304. Handler ETags are kept;no-storeresponses are skipped; gzipped responses carry the weak form of the tag. New dependency:crypto.- App-wide singletons:
registerSingleton(instance)andregisterSingletonFactory<T>((app) => ...)(created instart(), may be async), both with an optionaldispose. Read them withapp.singleton<T>(),ctx.singleton<T>()orService.singleton<T>(). - Lifecycle hooks:
onStart(after singletons, before serving) andonStop(after the server closes, reverse order, failures logged).init()runs the start-up half without a server (tests, custom servers); a failed start tears down what it set up.stop()disposes singletons in reverse order, then the cache and database. - Security headers on by default (
AppConfig.securityHeaders):Strict-Transport-Security(180 days),X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: no-referrer, andContent-Security-Policy: default-src 'none'; frame-ancestors 'none'on non-HTML responses (HTML gets a CSP only fromhtmlContentSecurityPolicy). Headers a handler sets are kept;securityHeaders: nullturns them off. Behaviour change: responses that had none of these headers now have them. JwtAuthenticator: verifies bearer JWTs and maps them to aPrincipal(sub,roles,scope/permissionsby default, or your owntoPrincipal, which can load the user and returnnullto reject). Tokens must use an algorithm fromalgorithmsthat fits the key (nonone, no RSA public key as an HMAC secret) and carry anexp;exp/nbf/iatallowleeway(30 s);issuer,audience(any of),maxAgeandrequiredTypeare optional. Rejections are 401 with codetoken_expiredorinvalid_token.JwtSignerissues matching tokens.JwtKeycovers HMAC (at least 32 bytes), RSA and EC PEM keys and JWKs;StaticJwtKeySetpicks keys bykidfor rotation;RemoteJwksloads an identity provider's JWKS with caching and early refresh on unknownkid. New dependency:dart_jsonwebtoken(signatures only; claim checks are gisila's).package:gisila/testing.dart:GisilaTestClientsends requests throughapp.buildHandler()in memory (get/post/ ... withjson:,form:,query:;withToken,withHeaders, andas(principal)with the newTestAuthenticator).TestResponseexposesjsonMap,errorCodeand the rest of the error envelope.
0.3.0 — 2026-10-28 — pipeline hardening (BREAKING) #
-
Security: code generation matched annotations by name and by any library URI containing "gisila", so a
Publicfrom another package (saygisila_extras) made a route public and dropped the class's@RequireAuth. Annotations must now come frompackage:gisila/. -
@Get('/')under@Controller('/users')answers both/users/and/users(it used to 404 on/users). -
stop(drainTimeout:)waits for in-flight requests (30 s by default) and then force-closes; it now also calls the newDatabaseProvider.dispose().start(stopOnSignals: true)stops gracefully on SIGINT/SIGTERM.AppConfig.healthCheckPath(e.g.'/healthz') serves a liveness probe outside auth and routing, with an optionalhealthCheck(503 on false). -
Defaults: no
Serverheader and noX-Powered-Byunless set (serverHeader,poweredByHeader). Unmatched routes answer a JSON 404 in the error envelope. In JSON logs, fields can no longer overwritets,level,msg. -
Docs: the pipeline order in
doc/middleware.mdmatches the code, and the library example usesregisterController(attacher: ...). -
Rate limits can be shared across isolates and processes:
AppConfig.rateLimitStoretakes aRateLimitStore(implementtakeon Redis, for example); the defaultInMemoryRateLimitStorekeeps today's per-isolate behaviour. Generated routes passgisilaRoute(routeId: 'METHOD path')so each route's buckets have the same name in every isolate.rateLimitMiddlewaretakes optionalstoreandscope. -
Fix:
RouteConfig(timeout: ...)andCorsConfig(maxAge: ...)set in an annotation were dropped by code generation on current Dart SDKs (the emitter read theDurationconstant's old private field). Routes now get their timeout. -
Tests:
pipeline_integration_testruns a generated controller (test/fixtures/guarded_controller.dart) throughbuildHandler(): guards, form and parameter binding, route timeout and rate limit, error mapping, CORS pre-flight, request ids.generated_golden_testfails when the generated code for that fixture changes (GISILA_UPDATE_GOLDEN=1to accept it).
Security #
- Rate limiter keys on the real client. The default key is now the
socket's peer address (it used to be the same string for every client).
X-Forwarded-Foris only trusted fromAppConfig.trustedProxies/RateLimitConfig.trustedProxies(exact IPs or CIDR), which defaults to loopback so apps behind a local nginx/Caddy keep working. Idle buckets are swept and the map is capped byRateLimitConfig.maxBuckets.Retry-Afteris now the real wait. New helper:clientAddress(request, trustedProxies:). - Body size limits hold for chunked bodies.
maxRequestBodyBytes/RouteConfig.maxBodyBytesnow meter the body stream and fail with413(PayloadTooLarge) as soon as the cap is crossed. Multipart parsing caps parts (maxParts, default 1000) and text field size (maxFieldBytes, default 1 MiB). - Route guards fail closed.
gisilaRouteuses the app it was built with, so guards hold even when the router is mounted outsidebuildHandler().guardRequestreturns500for a guarded route with noGisilaAppon the request (it used to let the call through). - Incoming
X-Request-Idvalues are only reused when they are 1–128 characters of[A-Za-z0-9._:-]. - CORS (breaking for one config).
CorsConfig(allowCredentials: true)with the default'*'origins now throwsArgumentErrorwhen the middleware is built, instead of echoing every origin with credentials; list the allowed origins. Only real pre-flights (OPTIONSwithOriginandAccess-Control-Request-Method) are answered by the middleware; one from a disallowed origin gets403, and otherOPTIONSrequests reach the router. Non-wildcard configs sendVary: Originon every response. - Authenticator errors stay on the server. An exception thrown by the
Authenticatorused to be sent to the client as the 401 message (JWT or database details). It is now a plain401 Authentication required, logged at warning level; anHttpException401/403 the authenticator throws on purpose is still sent as is.
Fixed #
- Multi-value response headers (several
Set-Cookie) are no longer joined into one by the CORS, request-id and server-header middleware. - The DB session middleware now runs inside CORS, rate limiting, the body cap
and the error mapper: pre-flights and rejected requests don't take a pooled
connection, and a failing
DatabaseProvider.openis a normal JSON500. A thrownHttpExceptionbelow 500 or a form validation error still closes the session withok: true. - Timeouts: a timed-out handler keeps running (Dart can't abort it), so the
session now stays open until it finishes and is then closed with
ok: false.RequestContext.cancellationis cancelled on timeout; checkisCancelledor callthrowIfCancelled()in long handlers. ATimeoutExceptionthrown by the handler itself is no longer reported as504. - CORS responses that echo a specific origin send
Vary: Origin. @Publicsurvives later config layers: a methodconfig:, named middleware or an app-widedefaultRouteConfigwithrequireAuthno longer turns a public route back into a login-required one. A later layer that adds a guard itself still wins.- Generated handlers only wrap parameter binding in the
TypeError/FormatException→400catch. An error thrown by the controller method itself used to come back as a400echoing its text; it now reaches the error handler as a500. Regenerate withbuild_runner. RateLimitConfig.keyExtractorset in a route'sconfig:(a top-level function or a static method) is now carried into the generated code; the generator used to drop it, so every route keyed on the client address.- JSON responses send an enum without a
toJson()as itsname("red"); they used to sendtoString()("Color.red"). - An empty query value (
?page=) counts as not given for non-string parameters, so an optionalint? pageisnullinstead of a400. Strings keep''.
0.2.0 — MVC overhaul (BREAKING) #
This release reshapes gisila into a proper MVC framework. Every consumer must
update their bootstrap, controllers, and forms. There is no deprecation
period; the old form() helper and the __inner(Request) generated style
are gone.
Added #
- Typed
Form/FormFieldhierarchy (lib/src/runtime/forms/). Declare aFormsubclass with oneFormFieldper expected input (StringField,IntField,DoubleField,BoolField,DateTimeField,EmailField,PasswordField,JsonField,FileField). The framework parses, validates, and gives the controller a fully-populated typed instance. Only declared fields are read; values are the parsed type, never the rawString. RouteConfig(lib/src/runtime/route_config.dart). Per-route rate limit, timeout, max body size, content-type whitelist, CORS overrides, extra middleware, declarative permissions/roles, and success status code- all merged from
AppConfig.defaultRouteConfig←@UseRouteConfig← annotation guards ← method-levelconfig:.
- all merged from
@UseRouteConfig(RouteConfig(...))class-level annotation for controller-wide route defaults.config:parameter on every HTTP-verb annotation (@Get,@Post,@Put,@Patch,@Delete,@Head,@Options).DatabaseProvider<S>+dbSessionMiddlewarefor per-request DB session lifecycle.AppConfig.databaseplugs your driver in; controllers reach the session asctx.db<MySession>().DbErrorMapperfor translating driver-specific exceptions (e.g. Postgres23xxxconstraint codes) intoHttpExceptions before the generic500mapper.Servicebase class +app.registerService<T>(factory). A fresh service instance is materialised per request, the framework injectsRequestContext, and controllers receive it as a typed method parameter (no constructor wiring at the controller).RequestContext.db<T>()andRequestContext.service<T>()accessors.gisilaRoute(...)runtime helper that composes the per-route Shelf pipeline (rate limit, content-type, timeout, body cap, custom middleware, AuthN/AuthZ) and dispatches to a typed handler.EndpointExceptionfor arbitrary{statusCode, body}errors; the default error middleware renders it as the user-supplied JSON envelope.FormValidationExceptionmapping in the default error middleware produces a structured400with a per-field error map.
Changed #
@Get/@Post/ etc. now acceptconfig: RouteConfig?. The positionalpathargument is unchanged.@Controlleris unchanged, but you can pair it with the new@UseRouteConfig(...)for controller-wide defaults.@RequireAuth/@Permissions/@AnyPermission/@Roles/@Publicare unchanged in shape, but the generator now folds them into the per-routeRouteConfigand auth runs as a real middleware.RequestContextcarries a service resolver in addition to the principal, requestId, request, extra; new methodsdb<T>()andservice<T>().AppConfiggainsdatabase,dbErrorMapper,defaultRouteConfig.- Default
serverHeaderbumped togisila/0.2.0.
Removed (BREAKING) #
form(request, fields: [...])map helper. Replaced by the typedForm/FormFieldhierarchy +bindForm<F>(request, F.new). Migration: extract the per-endpoint field lists into aFormsubclass per endpoint, and read values viaform.fieldName.value.FieldValidator<T>(old class) /EmailVerifier/Field/emailFieldValidator/nameFieldValidator. UseStringFieldwith validators,EmailField,PasswordField, etc.FieldValidationException. Replaced byFormValidationExceptionwhich carrieserrors: Map<String, String>(the olderrorwasMap<String, dynamic>).- Inline
guardRequest(...)calls in generated handlers. AuthN/AuthZ now runs as a per-route middleware composed fromRouteConfig. __inner(Request request)closure in generated handlers. Replaced by a typedhandler: (RequestContext ctx) async { ... }passed togisilaRoute(...).
Migration #
- Replace
form(request, fields: [...])callsites with a typedFormsubclass and accept it as a controller parameter. - Add
config: RouteConfig(...)to route annotations that need per-route limits or middleware. - Define a
DatabaseProviderfor your driver, setAppConfig.database, drop hand-writtenDatabase.connect(...)calls from controllers, and read sessions viactx.db<MySession>(). - Move business logic + DB access into
Servicesubclasses, register them withapp.registerService<T>(T.new), and accept them as controller parameters. - Delete any user-land
handleRequest(...)wrapper - the framework's default error middleware now mapsHttpException,FormValidationException,EndpointException, and (viaDbErrorMapper) driver-specific errors.
0.1.1 #
- Unified version with the rest of the gisila ecosystem (
gisila_doc,gisila_orm,gisila_studio). - Added
forms.dart:FieldValidator,EmailVerifier, and theform()helper for declarative request-body validation across JSON,application/x-www-form-urlencoded, andmultipart/form-data. - Added
content_typemiddleware: rejectsPOST/PUT/PATCHrequests with an unsupportedContent-Typewith a415 Unsupported Media TypeJSON envelope. - Added
body_parser.dart:readJsonBody,readFormBody, andreadBodyhelpers for content-type-aware payload parsing; used by the code generator for typed body parameters. - Added
FormDataabstraction for multipart and URL-encoded payloads.
0.1.0 #
- Initial release.
- MVC-style controllers via
@Controller+ HTTP verb annotations. - Build-time code generator (
build_runner/package:gisila_web/builder.dart) emitting anattachToApp(GisilaApp, Router)extension method per controller. - Declarative permission/role gates:
@RequireAuth,@Permissions,@AnyPermission,@Roles,@Public. - Pluggable
Authenticator/PermissionResolverplus a built-inStaticTokenAuthenticatorandClaimsPermissionResolver. GisilaAppapplication bootstrap with configurable global pipeline: request-id, structured access log (text or JSON), CORS, rate-limit, request timeout, body-size limit, error mapping.Loggerabstraction +ConsoleLogger; per-request structured logging middleware.- HTTP-error class hierarchy (
HttpException,BadRequest,Unauthorized,Forbidden,NotFound,Conflict,TooManyRequests,InternalServerError) rendered as a uniform JSON envelope. - JSON codec helpers (
coerce,readJsonBody,jsonResponse,emptyResponse) shared between hand-written and generated code. - Working
example/app with user CRUD, role-gated audit endpoint and public health-check.