Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Auth and Integrations

These go beyond cx.login, cx.user and sessions. All are opt-in.

Roles and CORS

let admin = cx.need(&USERS, |u| u.admin)?; // Row<User>

A signed-out user gets the error from cx.user (303 to sign in, 401 for a JSON client). A signed-in user who is not allowed gets a 403.

fn before(cx: &mut Cx) -> Result {
    cx.cors("*")?; // or "https://app.example.com https://x.com"
    Ok(())
}

A preflight is answered with a 204 and the headers, carried as the Err that ? returns. A site not listed gets no access-control-allow-origin.

let t = wisp::token("reset", &user.id, Duration::from_secs(3600));
let id: u64 = wisp::untoken("reset", &t)?; // 400 for any failure, the same one
  • HMAC-SHA256 under WISP_SECRET (and WISP_SECRET_OLD) over purpose, payload and expiry. A purpose of "" is none.
  • A release server whose app signs (sign-ins, signed cookies, tokens, OAuth) does not start without WISP_SECRET; it says what to set (openssl rand -hex 32). If signing happens anyway (an edge instance), the server fails closed: it refuses sign-ins, signed cookies, tokens and guarded forms until the secret is set. A guarded form then answers 422 "This form cannot be accepted right now." (a visitor is told nothing of the server's setup); stderr says once to set WISP_SECRET, and a test run in release (cargo test --release) needs one too: a .env with WISP_SECRET in the app's folder.
  • The payload is readable but not forgeable. Keep secrets out of it.
  • A token works until it expires. For a reset, put in it something that changes when the token is used, such as wisp::hex(&wisp::hmac_sha256(hash, "reset")) from the password hash (never the hash itself), and compare.
  • wisp::untoken_once("reset", &t)? also uses the token up: the same token again gives the same 400. Used tokens live in this process's memory until they expire (65,536 at most, and 16,384 for each purpose: a full store first deletes the expired ones, then refuses new ones of the full purpose and never forgets a used one), so it holds on one server, not across servers or restarts. Not in the edge build.

Abuse: Limits, Lockouts and Forms Bots Cannot Post

No JavaScript, no other site, no puzzle. It is for sites where all visitors may share one address, such as a Tor onion service.

static SIGNUPS: RateLimit = RateLimit::per_hour(3);
static LOGINS: Backoff = Backoff::new(5, Duration::from_secs(30));

fn signup(cx: &mut Cx, name: String, password: Password) -> Result {
    cx.limit(&SIGNUPS)?;
    cx.signup(User { name, password }).await?;
    redirect("/")
}

fn login(cx: &mut Cx, name: String, password: String) -> Result {
    // 429 while locked, before any hashing; a 422 counts as a failure
    LOGINS.run(&name, cx.login(&name, &password)).await?;
    redirect("/")
}
  • cx.visitor() is the Visitor to count a client by (a key for RateLimit and Backoff): the client's address (WISP_CLIENT_IP_HEADER, else the peer's, the /64 for IPv6), or for a request through Tor a ticket. A request is from Tor when its Host ends in .onion and the TCP peer is local or private. WISP_ONION=on says every request is from Tor and off says none is (for a proxy that rewrites Host).
  • The ticket is a random id signed with WISP_SECRET into the session cookie wv. Nothing is stored. A visitor without one is the shared "anonymous" visitor and receives one. Without a secret there are no tickets.
  • cx.limit(&LIMIT)? counts the request against a RateLimit by cx.visitor(). For Tor it also counts against the whole site's allowance (eight visitors' worth), so made-up tickets cannot multiply a limit. In a form action the 429 shows the form again with the typed text, the wait in words and retry-after. const RATE_LIMIT does the same for a route. An export does not count.
  • Backoff::new(free, first) locks a key out after free failures for first, then twice that, up to an hour. .up_to(d) changes the limit. run(key, attempt) checks the lock and runs the attempt; a 401 or 422 counts as a failure, any other error leaves the count, a success forgets it. check, fail and clear do the parts by hand. A locked name costs no password hashing and looks the same as a name that does not exist.
  • Key a lockout by the name guessed at. Anyone can then lock a name, so nest a second Backoff on (&name, cx.visitor()) with fewer free tries: BY_NAME.run(&name, BY_VISITOR.run((&name, visitor), attempt)).
  • Both are in memory, per server, and bounded: a flood of made-up keys makes the oldest forgotten.

Forms Bots Cannot Post

<form action="?/join" fields guard />

guard on a page form adds three things, and the action runs only if all hold:

  • a hidden token, signed over this page, this action and the visitor's ticket.
  • a field a person never sees, website_url, in a <div hidden>, which a script that fills every field fills.
  • a clock: a token sooner than two seconds after it was drawn, or later than twelve hours, is refused. Each token works once (up to 65,536 are kept, apart from untoken_once tokens).

A refusal is a 422 that shows the form again with the typed text, a new token and the reason. A person meets it only by sending within two seconds, after twelve hours, or with cookies refused.

A valid token also lets through a browser post that sends neither a usable Origin (null, from a page with Referrer-Policy: no-referrer) nor Sec-Fetch-Site. A post from another site or with Sec-Fetch-Site: cross-site is refused with a token as without. Forms in a layout or posting to a +server.rs have no token and rely on Sec-Fetch-Site: same-origin.

guard needs the native server; the edge build refuses guarded forms with a 501. A layout or a component with a guard form is a build error.

Light Pages and Print

A page that needs no browser code carries none: no inline script, no module preload, no outside font or image, one stylesheet (/_app/app.css), and one same-site script tag for the router that a browser with scripts off never fetches. examples/nojs is a whole app (sign up, sign in, a one-use recovery link, posts, comments, search, paging, a theme set by a form cookie), tested as a visitor with scripts off. Its stylesheet follows prefers-color-scheme, has visible focus, a skip link and a @media print block that hides the controls and writes each link's address. Save-Data and prefers-reduced-data need nothing from the server.

Two-Factor Codes

let secret = wisp::totp::secret(); // keep with the user
let uri = wisp::totp::uri("My App", &user.email, &secret); // QR code or text
static TRIES: Backoff = Backoff::new(5, Duration::from_secs(30)); // by user
let step = TRIES.run(&user.id, async {
    // ±1 step (30 s); None for a wrong code or one no later than the last
    wisp::totp::check(&user.totp, &code, user.totp_step).ok_or(Error::new(422, "Wrong code"))
}).await?;
user.totp_step = Some(step); // save it: the same code is refused next time

RFC 6238, SHA-1, six digits. check refuses any code no later than the step of the user's last good code, and the server also remembers the steps it took, so two requests with one code cannot both pass. Save the step with a compare-and-set. Six digits can be guessed, so put a Backoff on the check, by user.

Outbound HTTP

let mut req = wisp::Request::new("POST", "https://api.example.com/rows");
req.header("authorization", &format!("Bearer {key}"));
req.body = json.into_bytes();
let reply = wisp::fetch(req).await?; // reply.status, reply.text()
  • http:// works as is. https:// needs the tls feature (wisp = { version = "..", features = ["tls"] }), which uses rustls, no OpenSSL.
  • One request per connection, no redirects, 30 s, 64 KB of reply head (the interim heads, such as 103, count too), 16 MB of reply (fixed, no knob). Errors name the host only. A reply is chunked only when chunked is the last coding of transfer-encoding. Else Wisp reads it until the server closes.
  • wisp::fetch_follow(req, 5).await? follows up to 5 redirects (301, 302, 303, 307, 308), each as its own call with the limits above. A 303, or a POST answered by 301 or 302, becomes a GET with no body; 307 and 308 keep the method and body, to the same origin only (a 307 or 308 that would carry a body to another origin is a 502 a redirect would send the body to another origin). When the next URL has another origin (scheme, host or port), it is called only if it resolves to public addresses (a redirect to 127.0.0.1, 169.254.169.254 or a private network is a 502 not a public address, so a server you called cannot aim you inward), and every request header is dropped but accept, accept-language, accept-encoding and user-agent. A chain across hosts of your own network, or an internal http:// to https:// redirect (another origin too), is yours to walk with wisp::fetch and a loop. A redirect from https:// to http://, or to a scheme other than http(s), is refused (502), as is going past the 5 (502 too many redirects). wisp::on_fetch runs on every hop with a wisp::Hop (hop.n, 0 for the first call; hop.moved, a redirect took the chain to another origin), so it can refuse a host: wisp::on_fetch(|r, _| if !r.target.starts_with("https://api.example.com/") { r.target.clear() }) makes that call a 500 and ends the chain. A secret header goes only where the chain has not moved: wisp::on_fetch(|r, hop| if !hop.moved { r.header("x-key", KEY) }); added on every hop, a redirect would carry it to another server.
  • wisp::fetch_public(req, 5).await? is fetch_follow for a URL a visitor chose (a webhook target, a link preview): the first call is held to public addresses too, before a byte is sent. Loopback, private, link-local, CGNAT, multicast, documentation and every other IANA special-purpose range that is not globally reachable is a 502 not a public address, IPv6 forms that reach IPv4 too (mapped, NAT64 64:ff9b::/32 with its local-use /48, 6to4 2002::/16, Teredo 2001::/32). The address checked is the one connected to. At most 16 such calls (with /_img remote pictures) run at once; more wait their turn within the 30 s.
  • In the edge build it is the host's fetch, with redirect: 'manual' (a 3xx comes back, as here); a failure's reason has every URL in it cut to its host.

Streamed replies

wisp::fetch_stream(req) reads the reply as it arrives: a wisp::Upstream once the head is in (status, headers, header(name)), its body a piece at a time with chunk().await? (at most 64 KB, None at the end), or passed on to the client with respond(). A chat route that proxies a model's server-sent events:

// src/routes/api/chat/+server.rs
const BODY_LIMIT: usize = 16 * wisp::KB; // 413 past it
static CHATS: RateLimit = RateLimit::per_minute(10);

#[model]
struct Ask {
    #[validate(len = 1..=4000)]
    text: String,
}

#[derive(Json)]
struct Msg { role: String, content: String }
#[derive(Json)]
struct Chat { model: String, stream: bool, messages: Vec<Msg> }

async fn post(cx: &mut Cx, body: Ask) -> Result<Response> {
    cx.limit(&CHATS)?; // 429 with retry-after
    let key = wisp::env("API_KEY").ok_or_else(|| Error::new(500, "API_KEY is not set"))?;
    // The upstream body is built here: the visitor picks the text, never the model or limits.
    let up = Chat { model: "deepseek-chat".into(), stream: true, messages: vec![Msg { role: "user".into(), content: body.text }] };
    let mut req = wisp::Request::new("POST", "https://api.deepseek.com/chat/completions");
    req.header("authorization", &format!("Bearer {key}"));
    req.header("content-type", "application/json");
    req.body = wisp::to_json(&up).into_bytes();
    Ok(wisp::fetch_stream(req).await?.respond())
}
  • respond() keeps the status, content-type, cache-control, a 3xx's location and, on the built-in server, a content-encoding (fetch_stream sends accept-encoding: identity in place of yours, so the body comes plain; an upstream that codes it anyway is passed as it came with vary: accept-encoding, chunked, with no content-length; the edge host's fetch decodes the body, so there the header is dropped), and sends each piece as it comes; nothing holds the whole body, so its size has no limit. The body is another server's served from your origin, so it never runs there: x-content-type-options: nosniff always, and content-security-policy: sandbox for any type but text/event-stream, JSON (application/json, +json, NDJSON), text/plain, application/octet-stream (an empty type becomes it), application/pdf and raster image/* (not SVG): upstream HTML or SVG shows with no script and no access to your cookies. A 1xx or a status past 599 is a 502; a 204, 205 or 304 goes out with no body.
  • The head must come within 30 s. Then the body may go 30 s without a byte, and the whole reply 5 minutes; past either it is a 504 from chunk, and respond() ends the body there (check the format's own end, such as [DONE]).
  • The client leaving drops the Upstream, which closes the upstream connection (on the edge, cancels the host's read).
  • on_fetch runs first on the built-in server, as for wisp::fetch. On the edge it is the host's fetch, read a piece per call.
  • At most 256 streams are open at once in the process (in the isolate, on the edge); one more is a 503 too many fetch streams at once, before a byte is sent.
  • fetch_stream does not check the address: the URL is the app's own (a model's API). For a URL a visitor named, wisp::fetch_stream_public(req).await? (built-in server) connects only to a name whose every address is public, the address checked being the one connected to (a 502 not a public address, as fetch_public), At most 8 such streams are open at once in the process, apart from fetch_public's 16 turns, so slow streams never starve fetch_public or remote /_img pictures; one more is a 503 too many public fetch streams at once. It follows no redirect.

Email

Not built in: send mail from an action with wisp::fetch or any HTTP client.

Sign in with GitHub, Google or OpenID Connect

// src/routes/auth/github/+server.rs
fn get(cx: &mut Cx) -> Result {
    wisp::oauth::github().start(cx)
}

// src/routes/auth/github/callback/+server.rs
async fn get(cx: &mut Cx) -> Result {
    let who = wisp::oauth::github().finish(cx).await?; // id, email (verified only), name
    let id = match USERS.find(|u| u.github == who.id) {
        Some(u) => u.id,
        None => /* sign up */,
    };
    cx.sign_in(id);
    redirect("/")
}
  • Keys: GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET (GOOGLE_..., and {NAME}_... for oidc(name, issuer).await?), or .keys(id, secret). A provider's name is a word: letters, digits and _ (github). oidc gives a 500 for another name.
  • Register {ORIGIN}{WISP_BASE}/auth/github/callback with the provider. Outside dev, set ORIGIN or use .redirect(url), else start and finish give a 500 naming ORIGIN. In dev without ORIGIN the callback uses the Host asked only when it is loopback (localhost, *.localhost, 127.0.0.0/8, [::1]). A .redirect(url) must be https:// (http:// on localhost, 127.0.0.1 or [::1], for tests) with no #, else a 500. An https OIDC issuer whose discovery names an endpoint that is not https is refused (502).

Wisp uses a random state in a signed 10-minute cookie, PKCE (S256), and for scope openid (Google, oidc) a nonce with iss, aud, azp, exp and sub checks (and RFC 9207 iss in the callback). The secret goes only in a POST body to an https endpoint, and no key or token reaches an error or log. Only a provider-verified email is returned (match accounts on id, not email). Every failure is the same 400.

Not Here

Not built in: a RateLimit shared between servers, automatic /_wisp/oauth/... routes, and SMTP or SES clients.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.