tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

214 lignes · 9164 octetsBrut · Historique

web

The pieces a server-rendered web app needs around std/http: replies as values, form decoding, a CSRF guard and CSRF tokens, the client's address, an access log, security headers, static files and signed tokens. Pure Louise; form decodes the requests and log writes the access log.

web/reply

A handler answers a Reply; respond turns it into a Response inside the app's Shell: the frame a page goes in, and what Missing (404) and Unreadable (400) show. view answers a fragment to htmx and a page to a browser; otherwise chains handlers that answer Missing for paths that are not theirs.

import web/reply.{type Reply, Missing, Notice, Page, Shell}

fn shell :: -> Shell
{
  Shell( fn title content { <html><title>{title}</title><body>{content}</body></html> }
  , Notice("Not found", <p>There is nothing here.</p>)
  , Notice("Bad request", <p>This request could not be read.</p>)
  )
}

fn route :: req: Request -> Response
{
  let answer = match http.segments req
  { [] -> Page("Home", <p>Welcome</p>)
  , _ -> Missing
  }
  reply.respond req (answer |> reply.otherwise fn { more req }) (shell ())
}

Status, WithCookie, Header and Trigger (an htmx HX-Trigger on the body) wrap another reply; too_many shown 60 is a 429 to retry in a minute. A Redirect is a 303, and an HX-Redirect for htmx.

web/forms

decoded (the body) and queried (the query string) run a form schema; a request the schema refuses is Unreadable.

fn create :: req: Request -> Reply
{
  forms.decoded req (sighting ()) fn seen { Redirect("/birds/{seen.bird}") }
}

web/guard

cross_site req is True for a request that changes something on behalf of another site's page (Sec-Fetch-Site, else Origin against Host): refuse it.

if guard.cross_site req { http.text 403 "Cross-site requests are refused." } else { route req }

web/csrf

CSRF tokens bound to a session, a port of toboggan's. key secret derives the session's key from its secret (an HMAC under a fixed label), so no store holds it. token key mints a fresh token for each response: base64url(16 random bytes) "." base64url(HMAC-SHA256(key, those bytes)). valid key token checks one that came back, in constant time. Every token minted for a session stays valid until the session ends; tokens are not single-use. The app sends a token with each response (an X-CSRF-Token header, a hidden _csrf field) and refuses a request that changes something without a valid one, after guard.cross_site.

let key = csrf.key session_secret
http.with_header resp "X-CSRF-Token" (csrf.token key)
if !csrf.valid key (option.unwrap_or (http.header req "X-CSRF-Token") "") { http.text 403 "..." } else { ... }

web/client

The client effect tells who sent a request; behind trusted handles it, believing X-Forwarded-For only from the trusted proxies.

client.behind ["10.0.0.1"] fn { log.info "{req.method} {http.path req}" [("client", client.address req)] }

web/access

logged access req handler runs the handler and logs one line for the request through the log package: method, path (without the query string), status, the handler's time, the client, and htmx=1 for an htmx request. The level says whether to look at it: a 5xx is Error, a 4xx Warn, any other answer to one of access.assets (prefixes; defaults has /static/, /favicon.ico, /.well-known/ and /robots.txt) Debug, and the rest Info. At Info, a page view is one line, not one per stylesheet and script.

let least = os.env "LOG_LEVEL" |> option.then log.level_named |> option.unwrap_or Info
use <- log.to_console least
use <- client.behind trusted
access.logged (access.defaults ()) req fn { route req }
// 2026-11-05T14:02:13.000Z info  GET /leaderboard 200 12ms client=127.0.0.1

An app that keeps client addresses out of its logs passes access.without_clients (access.defaults ()): its lines carry no client=, and the address is still there for the app to use (a rate limit, say) without being written down.

The line is written when the handler returns, so a streamed body may still be in flight, and a handler that panics writes none (a cleanup cannot log, ADR 0016).

web/security

harden adds a strict Content-Security-Policy (the site's own files only, nothing unsafe), nosniff, a same-origin referrer and opener, and no framing. with_script_nonce lets the inline scripts that carry a fresh nonce run too (a policy that allows that nonce already is left alone).

security.harden (route req) |> security.with_script_nonce _ nonce

harden_with policy is the fuller set, for pages that depend on who is signed in (toboggan's contextHeaders). A Policy gives the request's nonce, the Trusted Types policies the page's scripts may create, and whether the site is HTTPS:

  • the same Content-Security-Policy, with script-src 'self' 'nonce-…', and require-trusted-types-for 'script'; trusted-types … when names are given (none: Trusted Types are not required);
  • Cache-Control: no-store, no-transform, unless the response sets its own (static files keep their caching);
  • Referrer-Policy: no-referrer, nosniff, a Permissions-Policy that turns off the camera, microphone, geolocation, payment and USB, and same-origin opener and resource policies;
  • Strict-Transport-Security: max-age=31536000; includeSubDomains, only when the site is HTTPS.
let policy = Policy(nonce: nonce, trusted_types: ["htmx"], https: string.starts_with public_url "https://")
security.harden_with policy (route req)

web/assets

serve root caching segments answers a file under root with its content type, and the Cache-Control that caching gives its path. The types cover stylesheets, scripts, fonts, images (SVG, PNG, WebP, JPEG, AVIF, GIF, icons), web app manifests and JSON; any other file is application/octet-stream. A hidden segment or one holding a separator is not found, so a path never leaves root.

fn caching :: segments: List<String> -> String
{
  match segments { ["vendor", ..] -> "public, max-age=86400", _ -> "no-cache" }
}

("GET", ["static", ..rest]) -> assets.serve "static" caching rest

web/signed

sign key claims is "{claims}.{signature}" (HMAC-SHA256, base64); verified key token gives the claims back when the signature matches, compared in constant time (same_bytes, which csrf uses too). The claims are readable: sign what must not change, not what must stay secret. Expiry is the caller's, in the claims.

let token = signed.sign key "{user}.{expires_ms}"
match signed.verified key token { Some(claims) -> ..., None -> ... }

web/swap

The markup of a streamed page. The page goes out first, with a placeholder where each slow part will go. Then each part follows as it finishes, as a <template> followed by a <swap-in> marker. Then comes the end of the document. One inline script in the head, allowed by the response's nonce (security.with_script_nonce), defines <swap-in>. When the browser reads the marker, the script moves the template's content into the placeholder and fires swap-in:swapped on each new element.

An app may put swap.script nonce in every page's head itself (htmx's hx-csp extension wants a nonced script on every page). opened then leaves the head as it is, so the script goes in once.

swap.placeholder "swap-1" skeleton      // the skeleton, with id="swap-1" aria-busy="true"
swap.part "swap-1" (html.render labels) // <template>…</template><swap-in for="swap-1"></swap-in>
swap.script nonce                       // <script nonce="…">…</script>, for the head
swap.opened page nonce                  // Some((up to </body>, with the script in the head once, "</body></html>"))

web/parts

Parts of a page rendered by actors of their own. parts.start spawns a part's actor at once and answers its placeholder. parts.respond streams a page that started parts:

  • the page, up to its body's end;
  • each part as it finishes, or the fallback if it fails or misses the deadline;
  • then the end of the document.

A page of any status streams its parts: a 404 page's parts arrive as a 200 page's do. A page that started no parts, or a reply that is not a page (a redirect, a text reply), is answered as it is, and its parts are stopped. A part's actor gets none of the request's handlers (ADR 0004), so render re-installs whatever application effects it needs.

The nonce is the app's, in Settings: it makes one per request (base64 of 16 random bytes or more) and uses it everywhere, so the streamed page's policy and swap script carry the same nonce as the rest of the response.

let nonce = base64.encode (random.bytes 18)
let started = parts.new ()
let labels = parts.start started (nav_skeleton ()) fn { label_links (load_labels owner) }
parts.respond started Settings(timeout_ms: 5000, fallback: unavailable (), nonce: nonce) (page labels)

Tests

louise test here, and louise test --native for the native backend.