Tooling & production/Security & Hardening
Security & Hardening
CSP nonces, HSTS, CSRF, CORS, signed webhooks, auth/seal tokens, PHI redaction, audit logs, and Live session binding.
On this page
- Security Headers & CSP Nonces
- Alpine CSP Build vs Standard Alpine
- CSRF & Origin Protection
- CORS & Signed Webhooks
- Cross-Origin Resource Sharing (router/cors)
- Webhook Verification (router/webhook, billing/stripe)
- Compile-Time Guards (fletch check)
- Binding Authorization (W0201, W0207)
- Template & Directive Injection (W0313)
- PCI Card-Name Lint (W0314)
- Sealed Tokens & Signed URLs
- Authenticated Encryption Tokens (auth/seal)
- Expiring Signed URLs (auth/signedurl)
- Live Session Hardening
- PHI Redaction & Audit Logs
- Sensitive Values & Redacting Loggers (obs)
- Live State PHI Tagging
- Append-Only Audit Trails (audit, audit/postgres)
Fletch enforces security controls at two points: runtime middleware across router, auth, live, obs, and audit, and static analysis in fletch check. Most protections are active in the default scaffold, while specialized packages (auth/seal, auth/signedurl, router/webhook, obs, audit/postgres) handle tokens, third-party callbacks, sensitive data, and compliance logging.
Security Headers & CSP Nonces
The github.com/fletchhq/fletch/router/secure middleware sets transport and browser security headers on every response:
- Strict-Transport-Security (HSTS) for HTTPS enforcement
- Content-Security-Policy with a per-request cryptographic nonce (
script-src 'self' 'nonce-...') - Frame protection,
X-Content-Type-Options, andReferrer-Policyheaders
Each request gets a fresh nonce stored in the request context. Retrieve it with secure.Nonce(ctx) whenever you render an inline script tag in a Crest template:
<script nonce={ secure.Nonce(ctx) }>
window.APP_BOOT = { locale: "en-US" };
</script>
Fletch wires secure.Nonce(ctx) automatically into the Live client runtime script and into <f:alpine />. You do not need to pass a nonce attribute manually for built-in runtime tags.
Alpine CSP Build vs Standard Alpine
Fletch ships @alpinejs/csp by default so client-side Alpine directives execute under script-src 'self' 'nonce-...' without opening 'unsafe-eval'.
If you opt into the standard Alpine build (which relies on dynamic expression evaluation) while keeping a strict CSP that omits 'unsafe-eval', fletch check emits diagnostic W0315. Either switch back to the @alpinejs/csp build or explicitly add 'unsafe-eval' to your script policy if an external script requires it.
CSRF & Origin Protection
Cross-site request forgery protection lives in github.com/fletchhq/fletch/auth and is re-exported at the root package as fletch.CSRF.
Attach auth.CSRF (or fletch.CSRF) to browser route groups, then place <f:csrf /> inside every state-changing HTML form in your .crest templates:
<form method="POST" action="/settings/profile">
<f:csrf />
<input type="text" name="display_name" value={ user.DisplayName } />
<button type="submit">Save</button>
</form>
For defense in depth across non-form mutations and fetch calls, add auth.OriginProtection(trusted...) with your allowed origin list:
router.Use(auth.OriginProtection(
"https://app.example.com",
"https://admin.example.com",
))
Live WebSocket upgrades perform Origin checks against the same trusted origins before a socket connects or mounts state. Upgrade requests from unrecognized origins are rejected at handshake time.
CORS & Signed Webhooks
Cross-Origin Resource Sharing (router/cors)
Use github.com/fletchhq/fletch/router/cors on API route groups that accept browser requests from separate domains. Keep CORS middleware scoped to API routes rather than attaching wildcard rules globally across cookie-authenticated HTML routes.
Webhook Verification (router/webhook, billing/stripe)
Webhook endpoints accept unauthenticated external POST requests, so they must verify cryptographic signatures against the exact bytes received over the wire.
github.com/fletchhq/fletch/router/webhook handles three problems common to inbound webhooks:
- Reading and verifying the raw request body before any JSON parser touches it.
- Pluggable signature verification through the
Verifierinterface so each provider implements its own HMAC or asymmetric check. - Replay and deduplication protection to reject repeated deliveries and stale timestamps.
For Stripe webhooks, github.com/fletchhq/fletch/billing/stripe exposes three entry points depending on how much control you want over the handler:
stripe.VerifySignature: validates the Stripe signature header against the raw payload and signing secret.stripe.ConstructEvent: verifies the signature and decodes the verified payload into a typed Stripe event.stripe.Webhook: HTTP middleware/handler wrapper that handles raw-body reading, signature checks, and deduplication before invoking your handler.
Compile-Time Guards (fletch check)
fletch check inspects Go handlers, input structs, and .crest templates at build and CI time to catch missing authorization and injection vectors before deployment.
| Code | Target | What It Catches |
|---|---|---|
W0201 |
Binding input structs | Request input struct neither implements Authorize nor embeds fletch.Public |
W0207 |
Binding input structs | Trivial Authorize implementation (for example, unconditionally returning nil) |
W0313 |
.crest templates |
Dynamic Go expressions inside on*, srcdoc, or Alpine x-* / @* / :* directives |
W0314 |
.crest templates |
Named form inputs whose attributes match payment card field patterns (PCI lint) |
W0315 |
App / CSP config | Standard Alpine enabled without 'unsafe-eval' in CSP |
Binding Authorization (W0201, W0207)
Every handler input struct bound from an HTTP request must make its authorization policy explicit. Implement Authorize on protected inputs, or embed fletch.Public on intentionally unauthenticated endpoints:
type UpdateInvoiceInput struct {
InvoiceID string `path:"id"`
Status string `json:"status"`
}
func (in *UpdateInvoiceInput) Authorize(ctx context.Context) error {
user := auth.UserFromContext(ctx)
if user == nil || !user.CanEditInvoice(in.InvoiceID) {
return auth.ErrForbidden
}
return nil
}
type HealthPingInput struct {
fletch.Public
}
Omitting both triggers W0201. Writing a placeholder Authorize method that always returns nil triggers W0207. If a route is genuinely public, embed fletch.Public so reviewers and scanners can audit every public surface in one search.
Template & Directive Injection (W0313)
Crest auto-escapes normal HTML text and attribute values, but HTML escaping cannot make dynamic Go values safe inside executable attribute contexts. W0313 rejects dynamic Go expressions inside:
- Inline DOM event handlers (
onclick,onload,onerror, and anyon*attribute) srcdocattributes on iframes- Alpine directives (
x-*,@*, and:*)
Pass server data through plain data-* attributes or a nonce-protected JSON script block, and keep the Alpine expression static:
<!-- Rejected by W0313 -->
<div x-data={ "{ name: '" + user.Name + "' }" }></div>
<!-- Accepted -->
<div data-user-name={ user.Name } x-data="profileCard"></div>
PCI Card-Name Lint (W0314)
Payment card numbers, CVCs, and expiration fields should go straight from the browser to a tokenized payment iframe (such as Stripe Elements) rather than passing through Live component bindings. fletch check reports W0314 as a static heuristic across .crest templates when a <input>, <select>, or <textarea> with a name attribute matches payment-card patterns in its name, autocomplete, or related attributes (such as cardnumber, cvc, expmonth, or autocomplete="cc-number"). It is a static warning rather than a runtime guarantee: custom fields that evade the heuristic are not caught, and nothing stops card data from reaching Live frames or server memory at runtime. For PCI isolation, collect card details in a provider-hosted iframe such as Stripe Elements and send only the resulting token to your server.
Sealed Tokens & Signed URLs
Authenticated Encryption Tokens (auth/seal)
github.com/fletchhq/fletch/auth/seal creates compact, tamper-evident AEAD tokens for password resets, email confirmations, magic links, and short-lived encrypted payloads.
Create a sealer with seal.New(key, seal.WithClock(...), seal.WithPreviousKeys(...)), then encrypt values with Seal and verify/decrypt them with Open:
sealer, err := seal.New(
currentKey,
seal.WithClock(time.Now),
seal.WithPreviousKeys(previousKey),
)
Two properties keep tokens isolated and rotatable:
- Purpose binding ties every ciphertext to a caller-supplied purpose string. A token produced by
Sealfor"email-verify"will failOpenif presented to"password-reset". - Key rotation via
seal.WithPreviousKeyslets you deploy a new primary key immediately:Sealalways encrypts under the primary key, whileOpenaccepts tokens encrypted under either the primary key or any listed previous key until old tokens expire.
Expiring Signed URLs (auth/signedurl)
github.com/fletchhq/fletch/auth/signedurl signs URLs with an HMAC and expiration timestamp for one-click unsubscribe links, temporary download routes, and signed callbacks.
Construct a signer with signer, err := signedurl.New(secret). The secret is a []byte of at least 32 bytes; a shorter one returns an error:
Signappends a signature and expiration parameter to a URL.Verifychecks the signature and expiration on an incoming request.RequireSignatureacts as route middleware, rejecting unsigned, tampered, or expired requests before the handler runs.
Live Session Hardening
Live components stay open over long-lived WebSocket connections, so session revocation has to propagate past normal HTTP middleware.
In a Fletch app, build the session cookie with app.SessionCookie(secret, opts...). It wires revocation to (*fletch.App).EvictLiveBinding, so logging out, resetting a password, or revoking a user session immediately ends the matching Live sessions on every Live handler the app serves.
Outside the fletch meta-module, pair auth.WithOnSessionRevoked with (*live.Handler).EvictBinding yourself. The callback receives the session’s binding key:
auth.WithOnSessionRevoked(func(bindingKey string) {
liveHandler.EvictBinding(bindingKey)
})
Live runtime enforcement emits structured codes you can monitor in logs and alerts:
| Code | Meaning |
|---|---|
W6013 |
Live session ended after session revocation (EvictBinding) |
W6007 |
Live frame refused because its auth session binding does not match |
W6004 |
Client submitted a forged or stale Live handler reference |
W0429 |
Client exceeded rate limits on HTTP routes or Live events |
A sudden spike in W6004 usually points to an out-of-date tab or an attacker probing handler names; a spike in W0429 indicates abuse or a tight client retry loop.
PHI Redaction & Audit Logs
Applications handling protected health information (PHI), financial records, or regulated PII can enforce redaction at the type, logger, telemetry, and Live-state layers using github.com/fletchhq/fletch/obs and github.com/fletchhq/fletch/audit.
Sensitive Values & Redacting Loggers (obs)
Wrap regulated fields in obs.Sensitive[T] using obs.NewSensitive(v). Formatting, logging, or serializing the wrapper outputs a redacted placeholder unless application code explicitly unwraps the underlying value.
For structured logging, wrap your base slog.Handler with obs.NewRedactingHandler(base, allowlist...). Any attribute key outside the allowlist is redacted before log output leaves the process:
type PatientRecord struct {
ID string
SSN obs.Sensitive[string]
}
record := PatientRecord{
ID: "pat_104",
SSN: obs.NewSensitive("123-45-6789"),
}
handler := obs.NewRedactingHandler(
slog.NewJSONHandler(os.Stdout, nil),
"request_id",
"route",
"status",
"duration_ms",
)
logger := slog.New(handler)
Pair the redacting handler with two additional obs options when sending errors or traces to external observability backends:
obs.WithErrorRedactor: strips or masks sensitive values from error strings before error reporters record them.obs.WithDropQueryText: drops raw SQL query strings from telemetry spans so bound literals or sensitive table lookups never leave your database network.
Live State PHI Tagging
Add the fletch:"phi" struct tag to Live component fields that hold regulated values:
type IntakeForm struct {
Step int
PatientName string `fletch:"phi"`
DateOfBirth string `fletch:"phi"`
}
Fields tagged with fletch:"phi" are masked in Live state inspection outputs (/_fletch/ax/live_state) and Live diagnostic dumps.
Append-Only Audit Trails (audit, audit/postgres)
Use github.com/fletchhq/fletch/audit for recording who performed an action, when it happened, and which resource was accessed or modified. In production, wire the github.com/fletchhq/fletch/audit/postgres backend, which writes events to an append-only Postgres table designed for tamper-resistant compliance queries.