Meta tags:
description= Generate and verify CSRF tokens with Bun s built-in API;
Headings (most frequently used words):
csrf, bun, system, protection, documentation, index, on, this, page, generate, verify, using, with, serve, default, secret, typescript, get, started, core, runtime, file, module, http, server, networking, data, storage, concurrency, process, interop, tooling, utilities, standards, compatibility, contributing,
Text of the page (most frequently used words):
token (41), the (36), secret (32), bun (32), csrf (28), sessionid (23), #verify (21), generate (21), session (20), string (19), const (17), and (13), user (10), algorithm (8), default (8), this (7), page (7), encoding (7), type (7), req (7), options (6), server (6), form (6), bound (6), requester (6), hex (5), base64url (5), sha512 (5), for (5), isvalid (5), tokens (5), headers (5), when (5), with (5), used (5), file (5), documentation (4), number (4), expiresin (4), sha256 (4), typescript (4), both (4), per (4), runtime (4), new (4), return (4), visitor (4), one (4), match (4), returns (4), copy (4), protection (4), was (3), function (3), maxage (3), csrfalgorithm (3), base64 (3), use (3), true (3), same (3), thread (3), generated (3), console (3), response (3), csrftoken (3), get (3), formdata (3), getsessionid (3), submit (3), cookie (3), serve (3), null (3), request (3), has (3), identifier (3), only (3), using (3), must (3), during (3), principal (3), not (3), optional (3), key (3), encoded (3), hmac (3), utilities (3), system (3), built (2), secrets (2), transpiler (2), boolean (2), csrfverifyoptions (2), csrfgenerateoptions (2), interface (2), 256 (2), sha384 (2), blake2b512 (2), blake2b256 (2), types (2), always (2), shared (2), across (2), calls (2), uses (2), random (2), workers (2), log (2), _csrf (2), post (2), button (2), input (2), text (2), name (2), hidden (2), content (2), create (2), before (2), every (2), from (2), process (2), pass (2), issued (2), than (2), 1000 (2), age (2), fails (2), verification (2), any (2), without (2), none (2), milliseconds (2), own (2), 86400000 (2), sign (2), provided (2), memory (2), auto (2), description (2), option (2), object (2), parameters (2), expires (2), verifies (2), generates (2), timestamp (2), cross (2), site (2), api (2), contributing (2), node (2), compatibility (2), apis (2), toml (2), data (2), cookies (2), fetch (2), install (2), module (2), search (2), index (2), hosted, mintlify, developer, platform, powered, youtube, discord, github, next, previous, raise, issue, suggest, edits, yes, helpful, namespace, production, provide, explicit, your, infrastructure, within, context, you, omit, parameter, once, convenient, single, threaded, applications, but, won, servers, after, restart, url, listening, 403, status, invalid, typeof, await, async, send, message, value, method, action, httponly, samesite, lax, path, set, append, randomuuid, crypto, html, let, else, issuing, routes, placeholder, less, would, share, binding, yet, never, fall, back, resolve, csrf_secret, env, typical, pattern, rendering, embed, field, submitted, works, reject, older, minute, isvalid2, enforce, shorter, max, what, other, supplied, maximum, independent, required, valid, expired, otherwise, false, token2, different, that, hour, binds, requesting, equivalent, passed, format, until, defaults, hours, unique, contains, cryptographic, nonce, signature, ever, validates, attacker, can, obtain, their, replay, forged, victim, browser, are, signed, include, expiration, forgery, license, bindgen, building, windows, benchmarking, roadmap, web, globals, standards, utils, color, semver, glob, hashing, image, htmlrewriter, jsonl, json5, markdown, yaml, compiler, ffi, interop, tooling, cron, webview, spawn, shell, environment, variables, concurrency, redis, sqlite, sql, archive, binary, streams, storage, dns, udp, tcp, websockets, networking, metrics, error, handling, tls, routing, http, router, plugins, jsx, resolution, bunfig, repl, debugging, watch, mode, core, init, quickstart, installation, welcome, started, feedback, blog, reference, guides, test, runner, bundler, package, manager, navigation, home, skip, main, discover, all, available, pages, exploring, further, complete, docs, llms, txt,
Text of the page (random words):
csrf protection bun documentation index fetch the complete documentation index at docs llms txt use this file to discover all available pages before exploring further skip to main content bun home page search k install bun search navigation utilities csrf protection runtime package manager bundler test runner guides reference blog feedback get started welcome to bun installation quickstart typescript typescript 6 and 7 bun init bun create core runtime bun runtime watch mode debugging repl bunfig toml file module system file types module resolution jsx auto install plugins file system router http server server routing cookies tls error handling metrics networking fetch websockets tcp udp dns data storage cookies file i o streams binary data archive sql sqlite s3 redis concurrency workers process system environment variables shell spawn webview cron interop tooling node api ffi c compiler transpiler utilities csrf protection secrets console toml yaml markdown json5 jsonl htmlrewriter image hashing glob semver color utils standards compatibility globals bun apis web apis node js compatibility contributing roadmap benchmarking contributing building windows bindgen license on this page bun csrf generate bun csrf verify using with bun serve default secret typescript utilities csrf protection copy page copy page generate and verify csrf tokens with bun s built in api copy page copy page bun csrf generates and verifies csrf cross site request forgery tokens tokens are signed with hmac and include an expiration timestamp csrf ts generate a token bound to the requester s session const token bun csrf generate my secret sessionid user session id verify it const isvalid bun csrf verify token secret my secret sessionid user session id console log isvalid true always pass a sessionid the requester s session identifier or user id to both generate and verify without it a token is only bound to the secret any token the server has ever issued validates for every user so an attacker can obtain a token in their own session and replay it in a forged cross site request from a victim s browser bun csrf generate generate a csrf token the token contains a cryptographic nonce a timestamp and an hmac signature encoded as a string generate ts const token bun csrf generate my secret key parameters secret string optional the secret key used to sign the token if not provided bun generates a random in memory default secret unique per thread options object optional option type default description expiresin number 86400000 milliseconds until the token expires defaults to 24 hours encoding string base64url token encoding format base64 base64url or hex algorithm string sha256 hmac algorithm sha256 sha384 sha512 sha512 256 blake2b256 or blake2b512 sessionid string none binds the token to the requesting principal session id user id or equivalent the token only verifies when the same sessionid is passed to verify returns string the encoded token generate options ts token bound to the requester s session that expires in 1 hour encoded as hex const token bun csrf generate my secret sessionid user session id expiresin 60 60 1000 encoding hex using a different algorithm const token2 bun csrf generate my secret sessionid user session id algorithm sha512 bun csrf verify verify a csrf token returns true if the token is valid and has not expired false otherwise verify ts const isvalid bun csrf verify token secret my secret key parameters token string required the token to verify options object optional option type default description secret string auto the secret used to sign the token if not provided uses the same in memory default as generate maxage number 86400000 maximum token age in milliseconds independent of the token s own expiresin encoding string base64url must match the encoding used during generate algorithm string sha256 must match the algorithm used during generate sessionid string none must match the sessionid used during generate a token bound to one principal fails verification for any other principal and a token generated without a sessionid fails verification when one is supplied returns boolean verify options ts verify a token bound to the requester s session const isvalid bun csrf verify token secret my secret sessionid user session id enforce a shorter max age than what the token was generated with const isvalid2 bun csrf verify token secret my secret sessionid user session id maxage 60 1000 reject tokens older than 1 minute using with bun serve a typical pattern is to generate a token when rendering a form embed it in a hidden field and verify it when the form is submitted pass the requester s session identifier as sessionid to both calls so the token only works for the user it was issued to server ts const secret process env csrf_secret my secret resolve the requester s session identifier from a session cookie returns null when the visitor has no session yet never fall back to a shared placeholder or every session less visitor would share one token binding function getsessionid req request string null return req headers get cookie match s session 1 null const server bun serve routes form req create a per visitor session before issuing the form so the token is bound to this visitor and no one else let sessionid getsessionid req const headers new headers content type text html if sessionid sessionid crypto randomuuid headers append set cookie session sessionid httponly samesite lax path const token bun csrf generate secret sessionid return new response form method post action submit input type hidden name _csrf value token input type text name message button type submit send button form headers submit post async req const sessionid getsessionid req const formdata await req formdata const csrftoken formdata get _csrf if sessionid typeof csrftoken string bun csrf verify csrftoken secret secret sessionid return new response invalid csrf token status 403 return new response ok console log listening on server url default secret if you omit the secret parameter in both generate and verify bun uses a random secret generated once per thread this is convenient for single threaded applications but tokens won t verify across servers or workers or after a restart default secret ts both calls use the same per thread default secret within this runtime context const token bun csrf generate const isvalid bun csrf verify token true for production use always provide an explicit secret shared across your infrastructure typescript types ts type csrfalgorithm blake2b256 blake2b512 sha256 sha384 sha512 sha512 256 interface csrfgenerateoptions expiresin number encoding base64 base64url hex algorithm csrfalgorithm sessionid string interface csrfverifyoptions secret string encoding base64 base64url hex algorithm csrfalgorithm maxage number sessionid string namespace bun csrf function generate secret string options csrfgenerateoptions string function verify token string options csrfverifyoptions boolean was this page helpful yes no suggest edits raise issue transpiler previous secrets next i x github discord youtube powered by this documentation is built and hosted on mintlify a developer documentation platform
|