# Slabs Documentation (Full Handbook) --- # Build your first Slabs app in 10 minutes You are going to build a working note-taking app from scratch. By the end of this tutorial, you will have a SQLite migration, two self-contained HTTP endpoints with co-located tests, and a running local server with live HTMX form updates. ## Prerequisites Install [mise](https://mise.jdx.dev/) so you have pinned versions of `rust`, standalone `tailwindcss` v4, and `cargo-nextest`. Install the `slabs` CLI from crates.io (or run it directly inside the Slabs workspace): ```bash cargo install slabs-cli ``` ## Create a new application Generate a standalone project and run `slabs doctor` to verify your toolchain and defaults: ```bash slabs new app quicknotes cd quicknotes slabs doctor ``` Look at the files `slabs new app` created: | File | Role | | --- | --- | | `Cargo.toml` | Declares `slabs-framework = "0.5"` (imported in Rust as `slabs`), `slabs-build = "0.5"`, `axum`, `maud`, `sqlx`, and safety lints including `unsafe_code = "forbid"`. | | `build.rs` | Calls `slabs_build::discover();` so Cargo registers every `.rs` file in `slabs//` and `jobs/` at compile time. | | `src/lib.rs` | Invokes `slabs::discover_slabs!();`, defines `MIGRATOR`, and exports `boot` plus a `#[cfg(test)]` `test_app` helper. | | `src/main.rs` | Calls `slabs::init_tracing()`, loads `AppConfig::from_env("quicknotes")`, boots the app, and binds the HTTP server. | | `assets/input.css` | Imports Tailwind CSS v4 and scans `../slabs` for utility classes. | | `Dockerfile` and `litestream.yml` | Multi-stage `cargo-chef` container build with pinned Litestream `v0.3.13` replication and `docker-entrypoint.sh`. | | `.claude/skills/` | Five bundled agent skills for authoring slabs, migrations, reviews, deploys, and incident fixes. | There is no `routes.rs`, `models/`, or `controllers/` folder anywhere in the tree. ## Add a SQL migration Create `migrations/0001_notes.sql` to define a `notes` table: ```sql CREATE TABLE IF NOT EXISTS notes ( id TEXT PRIMARY KEY NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_notes_created_at ON notes (created_at DESC); ``` Apply the migration to a local SQLite database and write the full schema snapshot to `schema.sql`: ```bash DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db migrate DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db dump-schema ``` Open `schema.sql`. It contains your `notes` table and the twelve system tables owned by Slabs (`slabs_sessions`, `slabs_jobs`, `slabs_incidents`, `slabs_audit_log`, and eight others). Read `schema.sql` before writing any new SQL query. ## Write a slab to list notes Create `slabs/notes/list_notes.rs`. Do not edit `src/lib.rs` or any router file. `slabs-build` discovers and registers this file on the next build. ```rust use axum::extract::State; use slabs::prelude::*; pub fn slab() -> SlabDef { SlabDef::get("/", handle) .name("notes.list_notes") .summary("Render the notes page and creation form") } #[derive(sqlx::FromRow)] struct NoteRow { id: String, body: String, created_at: String, } async fn handle(State(ctx): State) -> SlabResult { let notes: Vec = sqlx::query_as( "SELECT id, body, created_at FROM notes ORDER BY created_at DESC, id DESC LIMIT 50", ) .fetch_all(ctx.db.reader()) .await?; let styles = ctx.assets.stylesheet_urls(); let scripts = ctx.assets.behavior_urls(); Ok(html::document( "Quicknotes", &styles, &scripts, maud! { main class="max-w-2xl mx-auto p-6 space-y-6" { h1 class="text-2xl font-bold" { "Quicknotes" } form hx-post="/notes" hx-target="#notes-list" hx-swap="afterbegin" "hx-on::after-request"="this.reset()" class="flex gap-2" { input type="text" name="body" placeholder="Write a note..." required class="input flex-1"; button type="submit" class="btn" { "Save" } } section id="notes-list" class="space-y-2" { @for note in ¬es { article id=(format!("note-{}", note.id)) class="card p-3" { p class="text-sm" { (note.body) } p class="text-xs text-muted-foreground mt-1" { (note.created_at) } } } } } }, )) } #[cfg(test)] mod tests { use axum::http::StatusCode; #[tokio::test] async fn renders_home_page() { let app = crate::test_app().await; let res = app.get("/").await; assert_eq!(res.status, StatusCode::OK); assert!(res.text().contains("Quicknotes")); } } ``` Three mechanisms are at work in this file: 1. `ctx.db.reader()` executes the `SELECT` on the 16-connection read-only SQLite WAL pool. 2. `html::document(...)` loads Basecoat UI, HTMX 2, SSE, Idiomorph, Alpine.js 3, and your compiled Tailwind stylesheet from `/_slabs/vendor/` and `/assets/{hash}/...`. 3. `#[cfg(test)] mod tests` boots an isolated in-memory SQLite database through `crate::test_app().await`. ## Write a slab to create a note Create `slabs/notes/create_note.rs`. It validates form input, generates a prefixed ULID with `id::new("nte")`, inserts the row inside a `BEGIN IMMEDIATE` transaction, and returns an HTML fragment that HTMX prepends to `#notes-list`. ```rust use axum::{extract::State, http::StatusCode, Form}; use chrono::Utc; use serde::Deserialize; use slabs::prelude::*; pub fn slab() -> SlabDef { SlabDef::post("/notes", handle) .name("notes.create_note") .summary("Insert a note and return an HTML fragment") } #[derive(Debug, Deserialize)] pub struct Input { pub body: String, } async fn handle( State(ctx): State, Form(input): Form, ) -> SlabResult<(StatusCode, Markup)> { let body = input.body.trim().to_string(); if body.is_empty() { return Err(SlabError::validation("body", "note body cannot be blank")); } let note_id = id::new("nte"); let now = Utc::now().to_rfc3339(); let mut tx = ctx.db.begin().await?; sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)") .bind(¬e_id) .bind(&body) .bind(&now) .execute(&mut *tx) .await?; tx.commit().await?; let fragment = maud! { article id=(format!("note-{note_id}")) class="card p-3" { p class="text-sm" { (body) } p class="text-xs text-muted-foreground mt-1" { (now) } } }; Ok((StatusCode::CREATED, fragment)) } #[cfg(test)] mod tests { use axum::http::StatusCode; #[tokio::test] async fn creates_note_and_rejects_blank_input() { let app = crate::test_app().await; let bad = app.post_form("/notes", &[("body", " ")]).await; assert_eq!(bad.status, StatusCode::UNPROCESSABLE_ENTITY); let created = app.post_form("/notes", &[("body", "Ship Slabs")]).await; assert_eq!(created.status, StatusCode::CREATED); assert!(created.text().contains("Ship Slabs")); let list = app.get("/").await; assert!(list.text().contains("Ship Slabs")); } } ``` ## Format, check, and run the server Format both `src/` and the auto-discovered `slabs/` directory, then run the full 6-step `slabs check` gate (formatting, static `[security]` scan, Clippy, Rustdoc, doctests, and parallel tests): ```bash slabs fmt slabs check --no-docs ``` Compile Tailwind CSS and start the live development server: ```bash slabs dev ``` Open `http://127.0.0.1:3000`. Submit a note and watch HTMX prepend it without a full page reload. In development mode (`SLABS_ENV=development`), visit `http://127.0.0.1:3000/_slabs/manifest` to inspect the JSON route manifest and `http://127.0.0.1:3000/health/ready` to check database readiness. ## What you built - `slabs-build` discovered every `.rs` file in `slabs//` at compile time without a central router file. - `ctx.db.reader()` ran reads concurrently, and `ctx.db.begin().await?` opened a `BEGIN IMMEDIATE` write transaction. - Each slab carried its own input validation, SQL, HTML template, and isolated `#[tokio::test]` tests. Next, follow [Add live updates with SSE, HTMX, and Idiomorph](realtime-htmx-sse.md) to push live DOM updates and online presence to every connected browser. --- # Add live updates with SSE, HTMX, and Idiomorph Extend your Slabs app so changes made in one browser tab appear immediately in every other open tab. You will add an SSE stream with `ctx.realtime.sse_stream`, broadcast Maud HTML fragments with `ctx.realtime.publish_html`, morph regions in place with Idiomorph, track online participants with `ctx.realtime.track_presence`, and guard WebSocket upgrades with `validate_ws_origin`. ## How Slabs realtime works `AppCtx.realtime` is an in-process broadcast hub backed by `tokio::sync::broadcast`. Each named topic (such as `"board:brd_123"` or `"room:rm_456"`) holds a 256-message ring buffer. - `ctx.realtime.sse_stream(topic)` returns an Axum `Sse` response with a 15-second `"ping"` keep-alive comment. Slow receivers skip lagged events instead of disconnecting. - `ctx.realtime.publish_html(topic, event, html)` pushes an HTML fragment to every subscriber on `topic`. - `ctx.realtime.track_presence(topic, user_id, meta)` registers an online participant and returns a `PresenceGuard` that removes the entry automatically when the connection drops. - `html::document(...)` loads `/_slabs/vendor/htmx.min.js`, `/_slabs/vendor/htmx-ext-sse.js`, and `/_slabs/vendor/idiomorph-ext.min.js`, and attaches `hx-ext="morph"` on ``. ## Step 1. Add an SSE stream slab Create `slabs/realtime/notes_sse.rs`. Check authentication or room permissions first on private streams, then return `ctx.realtime.sse_stream(...)`. ```rust use axum::{extract::State, response::IntoResponse}; use slabs::prelude::*; pub fn slab() -> SlabDef { SlabDef::get("/notes/stream", handle) .name("realtime.notes_sse") .summary("Stream live note HTML fragments over SSE") } async fn handle(State(ctx): State) -> impl IntoResponse { ctx.realtime.sse_stream("notes:global") } #[cfg(test)] mod tests { use axum::http::StatusCode; #[tokio::test] async fn sse_route_is_registered_in_manifest() { let app = crate::test_app().await; let res = app.get("/_slabs/manifest").await; assert_eq!(res.status, StatusCode::OK); assert!(res.text().contains("/notes/stream")); } } ``` ## Step 2. Publish HTML after the database commit Publish to `ctx.realtime` only after `tx.commit().await?` succeeds. Browsers will never receive an event for a transaction that rolled back. Update `slabs/notes/create_note.rs`: ```rust use axum::{extract::State, http::StatusCode, Form}; use chrono::Utc; use serde::Deserialize; use slabs::prelude::*; pub fn slab() -> SlabDef { SlabDef::post("/notes", handle) .name("notes.create_note") .summary("Insert a note and broadcast it to SSE subscribers") } #[derive(Debug, Deserialize)] pub struct Input { pub body: String, } async fn handle( State(ctx): State, Form(input): Form, ) -> SlabResult { let body = input.body.trim().to_string(); if body.is_empty() { return Err(SlabError::validation("body", "note body cannot be blank")); } let note_id = id::new("nte"); let now = Utc::now().to_rfc3339(); let mut tx = ctx.db.begin().await?; sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)") .bind(¬e_id) .bind(&body) .bind(&now) .execute(&mut *tx) .await?; tx.commit().await?; let fragment = maud! { article id=(format!("note-{note_id}")) class="card p-3" { p class="text-sm" { (body) } p class="text-xs text-muted-foreground mt-1" { (now) } } }; ctx.realtime .publish_html("notes:global", "note_created", fragment.into_string()); Ok(StatusCode::NO_CONTENT) } ``` Returning `StatusCode::NO_CONTENT` from the form post lets the SSE stream insert the new element once for both the sender and every other connected viewer, so the page never renders duplicate rows. ## Step 3. Connect HTMX SSE in your page slab In `slabs/notes/list_notes.rs`, add `hx-ext="sse"`, `sse-connect="/notes/stream"`, and `sse-swap="note_created"` to the list container: ```rust section id="notes-list" hx-ext="sse" sse-connect="/notes/stream" sse-swap="note_created" hx-swap="afterbegin" class="space-y-2" { @for note in ¬es { article id=(format!("note-{}", note.id)) class="card p-3" { p class="text-sm" { (note.body) } p class="text-xs text-muted-foreground mt-1" { (note.created_at) } } } } ``` ## Step 4. Morph updated regions with Idiomorph When an event replaces a card, form, or modal body instead of appending a new row, use `hx-swap="morph:innerHTML"` or `hx-swap="morph:outerHTML"`. Idiomorph diffs the incoming HTML against the live DOM and patches only changed attributes and text nodes. Open inputs keep focus and scroll positions stay put. ```rust // Replace an existing board region in place when its columns change ctx.realtime.publish_html( &format!("board:{board_id}"), "board_updated", rendered_columns.into_string(), ); ``` In the HTML container: ```rust div id="board-columns" hx-ext="sse" sse-connect=(format!("/boards/{board_id}/stream")) sse-swap="board_updated" hx-swap="morph:innerHTML" { // Server-rendered columns } ``` ## Step 5. Track online presence and guard WebSockets `ctx.realtime` includes in-memory presence tracking for rooms, boards, and collaborative documents. Hold the returned `PresenceGuard` for the lifetime of the connection so the participant is removed automatically on disconnect. ```rust use serde_json::json; let _presence = ctx.realtime.track_presence( &format!("room:{room_id}"), &session.user_id, json!({ "name": user_name }), ); // List currently connected participants on the topic let online: Vec = ctx .realtime .list_presence(&format!("room:{room_id}")); ``` If a slab upgrades a connection to a WebSocket, validate the browser `Origin` header before accepting the upgrade to block Cross-Site WebSocket Hijacking (CSWSH): ```rust use axum::http::HeaderMap; use slabs::prelude::*; if !validate_ws_origin(&headers, &ctx.config.cors_origins) { return Err(SlabError::forbidden("cross-origin websocket blocked")); } ``` `validate_ws_origin` requires a valid `Origin` header matching either the request `Host` or an explicit origin configured in `SLABS_CORS_ORIGINS`. ## Step 6. Test realtime broadcasts and presence in isolation You do not need a browser to verify SSE broadcasts or presence tracking. Subscribe to the topic on `app.ctx.realtime` before calling the mutation slab: ```rust #[tokio::test] async fn create_note_broadcasts_html_fragment() { let app = crate::test_app().await; let mut rx = app.ctx.realtime.subscribe("notes:global"); let res = app .post_form("/notes", &[("body", "Broadcast test")]) .await; assert_eq!(res.status, axum::http::StatusCode::NO_CONTENT); let msg = rx.try_recv().expect("expected realtime message"); assert_eq!(msg.event, "note_created"); assert!(msg.data.contains("Broadcast test")); } ``` Run `mise exec -- cargo nextest run` to verify the test passes, then open two browser windows side by side with `slabs dev` to watch notes appear live. --- # Write an atomic transaction with a background job Use this guide when an HTTP endpoint must update one or more domain tables and schedule background work (email, webhooks, or audit logs) so both commit together or both roll back together. ## Open a `BEGIN IMMEDIATE` transaction Call `ctx.db.begin().await?` at the start of the write section. `begin()` opens a `BEGIN IMMEDIATE` transaction on the single-connection SQLite writer pool. Pass `&mut *tx` to `sqlx::query` and `&mut tx` to `ctx.jobs.enqueue_in_tx`. ```rust // slabs/orders/place_order.rs use axum::{extract::State, http::StatusCode, Json}; use axum_extra::extract::CookieJar; use chrono::Utc; use serde::{Deserialize, Serialize}; use serde_json::json; use slabs::prelude::*; pub fn slab() -> SlabDef { SlabDef::post("/api/orders", handle) .name("orders.place_order") .summary("Create an order and enqueue a confirmation email atomically") } #[derive(Debug, Deserialize)] pub struct Input { pub sku: String, pub quantity: i64, } #[derive(Debug, Serialize)] pub struct Output { pub order_id: String, } async fn handle( State(ctx): State, jar: CookieJar, Json(input): Json, ) -> SlabResult<(StatusCode, Json)> { let session = ctx.auth.require_session(&jar).await?; if input.quantity <= 0 { return Err(SlabError::validation("quantity", "must be greater than zero")); } let order_id = id::new("ord"); let now = Utc::now().to_rfc3339(); let mut tx = ctx.db.begin().await?; sqlx::query( "INSERT INTO orders (id, user_id, sku, quantity, created_at) VALUES (?, ?, ?, ?, ?)", ) .bind(&order_id) .bind(&session.user_id) .bind(input.sku.trim()) .bind(input.quantity) .bind(&now) .execute(&mut *tx) .await?; ctx.jobs .enqueue_in_tx( &mut tx, "send_order_receipt", json!({ "order_id": order_id, "user_id": session.user_id }), ) .await?; tx.commit().await?; Ok((StatusCode::CREATED, Json(Output { order_id }))) } ``` If any query fails before `tx.commit().await?`, SQLite rolls back both the `orders` insert and the `slabs_jobs` insert. ## Guard shared edits with an Optimistic Offline Lock When two users open the same editable record (such as a card, document, or project setting) and submit updates from separate HTTP requests, a plain `UPDATE ... WHERE id = ?` silently overwrites the first save. Prevent lost updates with an opt-in SQL Optimistic Offline Lock. Add a `version` column to shared editable tables in your migration: ```sql ALTER TABLE cards ADD COLUMN version INTEGER NOT NULL DEFAULT 1; ``` Include the client's `version` in the request payload, increment it atomically inside `WHERE id = ? AND version = ?`, and return `SlabError::conflict` (`409 Conflict`) when `rows_affected() == 0`: ```rust let mut tx = ctx.db.begin().await?; let res = sqlx::query( "UPDATE cards SET title = ?, body = ?, updated_at = ?, version = version + 1 WHERE id = ? AND version = ?", ) .bind(input.title.trim()) .bind(&input.body) .bind(&now) .bind(&card_id) .bind(input.version) .execute(&mut *tx) .await?; if res.rows_affected() == 0 { return Err(SlabError::conflict( "Card was modified by another request. Reload and retry.", )); } tx.commit().await?; ``` If you need to distinguish a deleted record (`404 Not Found`) from a stale version (`409 Conflict`), run a quick `SELECT 1 FROM cards WHERE id = ?` inside the same `rows_affected() == 0` branch before choosing between `SlabError::not_found` and `SlabError::conflict`. ### When not to use an Optimistic Offline Lock Keep `version` checks opt-in and only on shared editable records. Skip them for: - **Append-only rows** such as chat messages, events, audit logs, and ledger entries that are inserted once and never edited in place. - **Hot counters** such as view counts, vote totals, or stock decrements, where an atomic `UPDATE ... SET count = count + 1 WHERE id = ?` avoids unnecessary conflict retries. - **CRDT real-time collaborative documents** where concurrent edits merge at the character or operation level instead of rejecting whole-row saves. ## Customize queue name, retries, or delay Use `enqueue_with_options_in_tx` when a job needs a named queue, a custom `max_attempts`, or a delay in seconds: ```rust ctx.jobs .enqueue_with_options_in_tx( &mut tx, "send_order_receipt", "mail", json!({ "order_id": order_id }), 8, // max_attempts (default is 5) 30, // delay_seconds before eligible to run ) .await?; ``` Failed jobs retry with exponential backoff (`2^attempts` seconds, capped at 1024 seconds). Once `attempts >= max_attempts`, the worker marks the job `status` as `"dead"`. ## Dispatch outbound webhooks in the same transaction Call `ctx.webhooks.dispatch_in_tx` before committing when an action notifies external webhook subscribers: ```rust ctx.webhooks .dispatch_in_tx( &mut tx, &account_id, "order.placed", &json!({ "order_id": order_id }), ) .await?; ``` `dispatch_in_tx` inserts HMAC-SHA256 signed rows into `slabs_webhook_deliveries` and enqueues `"slabs.deliver_webhook"` jobs on the `"webhooks"` queue inside the same transaction. During live HTTP delivery (`SLABS_WEBHOOKS_LIVE=true`), `slabs-webhooks` uses a custom SSRF-safe DNS resolver that blocks loopback, private, link-local, metadata, and IPv4-mapped IPv6 addresses at connect time, disables HTTP redirects, enforces a 10-second timeout, and caps response reads at 2 KiB. ## Write the matching background job Create `jobs/send_order_receipt.rs`. `slabs-build` discovers every `.rs` file in `jobs/` at compile time and registers it with `JobRegistry`. ```rust // jobs/send_order_receipt.rs use serde_json::Value; use slabs::prelude::*; pub fn job() -> JobDef { JobDef::new("send_order_receipt", run) .queue("default") .max_attempts(5) .summary("Send an order receipt email") } async fn run(ctx: AppCtx, payload: Value) -> SlabResult<()> { let order_id = payload .get("order_id") .and_then(|v| v.as_str()) .ok_or_else(|| SlabError::bad_request("missing order_id"))?; let user_id = payload .get("user_id") .and_then(|v| v.as_str()) .ok_or_else(|| SlabError::bad_request("missing user_id"))?; let (email,): (String,) = sqlx::query_as("SELECT email FROM users WHERE id = ?") .bind(user_id) .fetch_one(ctx.db.reader()) .await?; ctx.mail .send(Email { from: String::new(), to: email, subject: format!("Order {order_id} confirmed"), text_body: format!("Your order {order_id} is confirmed."), html_body: None, }) .await?; Ok(()) } ``` Never call `ctx.mail.send(...)` inside an open database transaction. `Mailer::send` performs network I/O when Resend or SMTP is configured and writes to `slabs_mail_outbox` outside your transaction. Always enqueue a job inside `tx` and send email from the job handler. ## Attach a recurring schedule To enqueue a job on a fixed interval while the server runs, attach `ScheduleDef::every` in `src/lib.rs`: ```rust use serde_json::json; use slabs::{ScheduleDef, SlabsApp}; use std::time::Duration; let app = SlabsApp::boot(config, &MIGRATOR, collect_slabs(), collect_jobs()).await?; let app = app.with_schedules(vec![ ScheduleDef::every(Duration::from_secs(3600), "cleanup_expired", json!({})), ]); ``` ## Drain jobs synchronously in tests In your co-located `#[tokio::test]`, call `app.drain_jobs().await` to execute every ready queued job right away, or call `app.run_job_now("job_name", payload).await` to invoke one handler directly: ```rust let processed = app.drain_jobs().await; assert_eq!(processed, 1); let emails = app.sent_emails().await; assert_eq!(emails.len(), 1); assert!(emails[0].subject.contains("confirmed")); ``` ## Validate multiple input fields at once When an endpoint accepts several fields, collect all errors in one pass with `Validate::new()`. Calling `.finish()?` returns `Ok(())` when every check passes or `Err(SlabError::ValidationErrors(...))` (HTTP `422 Unprocessable Entity`): ```rust let mut v = Validate::new(); v.required("sku", &input.sku) .max_len("sku", &input.sku, 64) .email("receipt_email", &input.receipt_email) .one_of("priority", &input.priority, &["standard", "rush"]) .check("quantity", input.quantity > 0, "must be greater than zero"); v.finish()?; ``` `Validate` supports `required`, `min_len`, `max_len`, `email`, `url`, `one_of`, `check`, `push`, `is_empty`, `errors`, and `finish`. When validation fails, Slabs responds with HTTP 422 and sorted field keys: ```json { "error": "validation_error", "fields": { "quantity": ["must be greater than zero"], "sku": ["is required"] } } ``` ## Paginate lists with keyset cursors Avoid `OFFSET` scans and extra `COUNT(*)` queries by pairing `Pagination` with `CursorPage::from_rows`. Extract `Query(page): Query`, fetch `page.fetch_limit(default, max)` rows (`clamped_limit + 1`), and pass the `Vec` to `CursorPage::from_rows`: ```rust use axum::{extract::{Query, State}, Json}; use serde::Serialize; use slabs::prelude::*; #[derive(Debug, Serialize, sqlx::FromRow)] struct OrderRow { id: String, sku: String, created_at: String, } async fn handle( State(ctx): State, Query(page): Query, ) -> SlabResult>> { let limit = usize::try_from(page.clamped_limit(20, 100)).unwrap_or(20); let fetch_limit = page.fetch_limit(20, 100); let rows: Vec = if let Some(cursor) = &page.cursor { sqlx::query_as( "SELECT id, sku, created_at FROM orders WHERE id < ? ORDER BY id DESC LIMIT ?", ) .bind(cursor) .bind(fetch_limit) .fetch_all(ctx.db.reader()) .await? } else { sqlx::query_as( "SELECT id, sku, created_at FROM orders ORDER BY id DESC LIMIT ?", ) .bind(fetch_limit) .fetch_all(ctx.db.reader()) .await? }; let result = CursorPage::from_rows(rows, limit, |row| row.id.clone()); Ok(Json(result)) } ``` `CursorPage::from_rows` truncates `rows` to `limit`, sets `has_more` to `true` when the extra row existed, and sets `next_cursor` from the last retained row (or `None` on the final page). ## Record transactional audit logs Call `ctx.audit.record_in_tx` inside an open transaction to write an immutable entry into `slabs_audit_log` atomically with your domain update. If the transaction rolls back, the audit row rolls back too. ```rust let mut tx = ctx.db.begin().await?; sqlx::query("UPDATE rooms SET archived_at = ? WHERE id = ?") .bind(&now) .bind(&room_id) .execute(&mut *tx) .await?; ctx.audit .record_in_tx( &mut tx, Some(&session.user_id), "room.archived", "room", &room_id, &json!({ "reason": input.reason }), ) .await?; tx.commit().await?; ``` `record_in_tx` returns the generated `aud_` ID. Read audit history on the read pool with `ctx.audit.list_for_target("room", &room_id, 50).await?` or `ctx.audit.list_recent(50).await?`. Both return `Vec`. ## Verify inbound webhooks and block replays When your app receives webhooks from external providers (such as Stripe, GitHub, or another Slabs app), verify the raw request bytes before parsing JSON, check the timestamp window, and claim an idempotency key inside the same database transaction as your domain update: ```rust use axum::{ body::Bytes, extract::State, http::{HeaderMap, StatusCode}, }; use slabs::{prelude::*, webhooks::Webhooks}; async fn handle( State(ctx): State, headers: HeaderMap, body: Bytes, ) -> SlabResult { let secret = std::env::var("PROVIDER_WEBHOOK_SECRET") .map_err(|_| SlabError::internal("missing PROVIDER_WEBHOOK_SECRET"))?; let sig = headers .get("x-provider-signature") .and_then(|v| v.to_str().ok()) .ok_or_else(|| SlabError::unauthorized("missing signature"))?; if !Webhooks::verify_incoming_hmac_sha256(&secret, &body, sig, "sha256=") { return Err(SlabError::unauthorized("invalid webhook signature")); } let ts: i64 = headers .get("x-provider-timestamp") .and_then(|v| v.to_str().ok()) .and_then(|s| s.parse().ok()) .ok_or_else(|| SlabError::unauthorized("missing timestamp"))?; if !Webhooks::verify_timestamp_window(ts, 300) { return Err(SlabError::unauthorized("stale webhook timestamp")); } let event: serde_json::Value = serde_json::from_slice(&body) .map_err(|_| SlabError::bad_request("invalid JSON payload"))?; let event_id = event["id"] .as_str() .ok_or_else(|| SlabError::bad_request("missing event id"))?; let mut tx = ctx.db.begin().await?; let claimed = ctx .webhooks .claim_idempotency_in_tx(&mut tx, "provider", event_id) .await?; if !claimed { tx.commit().await?; return Ok(StatusCode::OK); } // Apply domain updates and enqueue jobs inside `tx`... tx.commit().await?; Ok(StatusCode::OK) } ``` Pass `""` as the `prefix` argument to `verify_incoming_hmac_sha256` when a provider sends a raw hex digest without `"sha256="`. `claim_idempotency_in_tx` runs `INSERT OR IGNORE INTO slabs_idempotency_keys` on `tx`. It returns `Ok(true)` on the first claim and `Ok(false)` on replays. If `tx` rolls back before commit, the key is released so the provider can retry cleanly. --- # Authenticate with sessions, magic links, and Bearer tokens Slabs puts explicit authentication helpers on `ctx.auth` and fixed-window rate limiting on `ctx.rate_limit`. Authentication never hides in route-group middleware. You call the exact guard you need on line 1 of each slab handler. ## Choose an authentication guard | Guard | Accepts | On failure | | --- | --- | --- | | `ctx.auth.optional_session(&jar).await?` | Active session cookie | Returns `Ok(None)` | | `ctx.auth.require_session(&jar).await?` | Valid session cookie | HTTP 401 `Unauthorized` | | `ctx.auth.require_admin(&jar).await?` | Valid session with `role == "admin"` | HTTP 401 or HTTP 403 `Forbidden` | | `ctx.auth.optional_auth(&jar, &headers).await?` | `Authorization: Bearer` token or session cookie | Returns `Ok(None)` | | `ctx.auth.require_auth(&jar, &headers).await?` | Valid Bearer token or session cookie | HTTP 401 `Unauthorized` | | `ctx.auth.require_write_auth(&jar, &headers).await?` | Valid Bearer token (`permission == "write"`) or session | HTTP 401 or HTTP 403 `Forbidden` | When a request includes an `Authorization: Bearer ...` header, `optional_auth`, `require_auth`, and `require_write_auth` validate only that Bearer token. They never fall back to the session cookie if the Bearer token is invalid. When `cookie_secure` is `true` (the default in `staging` and `production`), Slabs names the session cookie `__Host-slabs_session` (`Path=/`, `Secure`, `HttpOnly`, `SameSite=Lax`, no `Domain` attribute). In local development over HTTP (`cookie_secure == false`), the cookie name is `slabs_session`. ## Hash and verify passwords asynchronously with Argon2id Your application owns its `users` table in `migrations/`. `ctx.auth.hash_password`, `ctx.auth.verify_password`, and `ctx.auth.verify_password_constant_time` are `async` functions. They offload Argon2id onto `tokio::task::spawn_blocking` with a concurrency semaphore and a 1024-byte password cap so slow hashes never block the async runtime. Create a user and session cookie atomically inside one transaction: ```rust use axum::{extract::State, http::StatusCode, Json}; use axum_extra::extract::CookieJar; use chrono::Utc; use serde::Deserialize; use slabs::prelude::*; #[derive(Debug, Deserialize)] pub struct SignUpInput { pub email: String, pub password: String, } async fn handle( State(ctx): State, jar: CookieJar, Json(input): Json, ) -> SlabResult<(StatusCode, CookieJar)> { let email = input.email.trim().to_lowercase(); ctx.rate_limit.check(&format!("auth:signup:{email}"), 5, 300)?; let user_id = id::new("usr"); let password_hash = ctx.auth.hash_password(&input.password).await?; let now = Utc::now().to_rfc3339(); let mut tx = ctx.db.begin().await?; sqlx::query( "INSERT INTO users (id, email, password_hash, role, created_at) VALUES (?, ?, ?, 'member', ?)", ) .bind(&user_id) .bind(&email) .bind(&password_hash) .bind(&now) .execute(&mut *tx) .await?; let (_session, cookie) = ctx .auth .create_session_in_tx(&mut tx, &user_id, "member", 30) .await?; tx.commit().await?; Ok((StatusCode::CREATED, jar.add(cookie))) } ``` During sign-in, prefer `ctx.auth.verify_password_constant_time(&input.password, stored_hash.as_deref()).await?`. When `stored_hash` is `None`, it still runs an Argon2id check against a dummy hash so callers cannot measure response timing to enumerate registered emails. To verify against a known hash directly, call `ctx.auth.verify_password(&input.password, &stored_hash).await?`. To sign out, call `let clear = ctx.auth.destroy_session(&jar).await?;` and return `jar.add(clear)`. ## Sign in with single-use 6-character magic links `issue_magic_link` generates a 6-character code from an unambiguous alphabet (omitting `0`, `O`, `1`, and `I`) and stores only a keyed domain-separated HMAC bound to `(email, purpose)` in `slabs_magic_links`: ```rust // Step 1: Issue code and send email ctx.rate_limit.check(&format!("magic:req:{email}"), 5, 300)?; let issued = ctx.auth.issue_magic_link(&email, "sign_in", 15).await?; ctx.mail .send(Email { from: String::new(), to: issued.email.clone(), subject: "Your sign-in code".into(), text_body: format!("Enter code {} within 15 minutes.", issued.code), html_body: None, }) .await?; ``` When the user submits the code, pass `email`, `purpose`, and the submitted code to `consume_magic_link`. It strips non-alphanumeric characters, uppercases the code, verifies the keyed HMAC for `(email, purpose)`, and executes `DELETE ... RETURNING` so every code works at most once. After 5 failed attempts within 15 minutes for the same `(email, purpose)`, Slabs locks out the pair and deletes any pending codes. ```rust // Step 2: Consume code atomically and start a session ctx.rate_limit.check(&format!("magic:consume:{email}"), 20, 60)?; let consumed = ctx .auth .consume_magic_link(&email, "sign_in", &input.code) .await? .ok_or_else(|| SlabError::unauthorized("invalid or expired code"))?; // Look up or create the user for consumed.email, then create a session: let (_session, cookie) = ctx.auth.create_session(&user_id, &role, 30).await?; Ok((StatusCode::OK, jar.add(cookie))) ``` ## Issue and verify personal Bearer access tokens Personal access tokens let CLIs, scripts, and AI agents call your endpoints without browser cookies. Tokens start with `slb_` and are stored only as SHA-256 digests in `slabs_access_tokens`. ```rust // Require a browser session to mint a new token let session = ctx.auth.require_session(&jar).await?; let issued = ctx .auth .issue_access_token(&session.user_id, &session.role, "CI deploy script", "write") .await?; // Return `issued.token` once; plaintext tokens cannot be recovered later. ``` Protect API slabs with `require_auth` (read or write) or `require_write_auth` (requires `permission == "write"`): ```rust async fn handle( State(ctx): State, jar: CookieJar, headers: axum::http::HeaderMap, ) -> SlabResult> { let principal = ctx.auth.require_write_auth(&jar, &headers).await?; Ok(axum::Json(serde_json::json!({ "user_id": principal.user_id, "auth_kind": principal.auth_kind, "permission": principal.permission, }))) } ``` ## Rely on built-in CSRF, CORS, safe redirects, and safe blob responses Slabs ships defense-in-depth protections enabled by default in `slabs-http`, `slabs-html`, and `slabs-storage`: - Fetch Metadata and Origin CSRF middleware runs on every cookie-authenticated `POST`, `PUT`, `PATCH`, and `DELETE` request (controlled by `SLABS_CSRF_ENFORCE`, default `true`). It rejects requests with `Sec-Fetch-Site: cross-site` and checks `Origin` against the request `Host` or `SLABS_CORS_ORIGINS`. Requests authenticated with `Authorization: Bearer` and inbound webhook paths (`/webhooks*`, `/api/webhooks*`) are exempt. - Cross-origin CORS stays disabled unless you set a comma-separated allowlist in `SLABS_CORS_ORIGINS`. - For explicit double-submit form tokens, call `html::csrf_token(&ctx.auth, &session.id)` when rendering and `html::verify_csrf(&ctx.auth, &session.id, &form.csrf_token)?` on submission. - `htmx::redirect(path)` and `htmx::flash_redirect(...)` validate that `path` is a safe relative path and fall back to `"/"` on open-redirect inputs such as `//evil.com`. For deliberate external URLs, call `redirect_external(url)` explicitly. - `json_script("boot-data", &payload)?` renders `