new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

missing: authentication & authorization

10 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Bun.CSRF.generate() parameters and options

Bun.CSRF.generate(secret?: string, options?: CSRFGenerateOptions) generates a CSRF token. 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) with fields: expiresIn (number, default 86400000) — milliseconds until token expires, defaults to 24 hours; encoding (string, default "base64url") — token encoding format: "base64", "base64url", or "hex"; algorithm (string, default "sha256") — HMAC algorithm: "sha256", "sha384", "sha512", "sha512-256", "blake2b256", or "blake2b512"; sessionId (string, default none) — binds the token to the requesting principal; the token only verifies when the same sessionId is passed to verify(). Returns a string containing the encoded token.

Bun.CSRF.verify() parameters and options

Bun.CSRF.verify(token: string, options?: CSRFVerifyOptions) verifies a CSRF token. Parameters: token (string, required) — the token to verify. options (object, optional) with fields: secret (string, default auto) — the secret used to sign the token; if not provided, uses the same in-memory default as generate(); encoding (string, default "base64url") — must match the encoding used during generate(); algorithm (string, default "sha256") — must match the algorithm used during generate(); maxAge (number, default 86400000) — maximum token age in milliseconds, independent of the token's own expiresIn; sessionId (string, default none) — must match the sessionId used during generate(); a token bound to one principal fails verification for any other principal. Returns a boolean: true if the token is valid and has not expired, false otherwise.

Bun.CSRF signs tokens with HMAC

Bun.CSRF generates and verifies CSRF tokens by signing them with HMAC. Each token includes an issue timestamp and an expiry duration.

CSRF tokens must include sessionId for security

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, so any token the server has ever issued validates for every user. An attacker can obtain a token in their own session and replay it in a forged cross-site request from a victim's browser.

Default CSRF secret is per-thread

If the secret parameter is omitted in both generate() and verify(), Bun uses a random secret generated once per thread. The default secret is convenient for single-threaded applications, but tokens do not verify across servers or workers, or after a restart. For production use, always provide an explicit secret shared across your infrastructure.

Bun.CSRF with Bun.serve() form pattern

A typical CSRF protection pattern with Bun.serve() 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. Create a per-visitor session before issuing the form so the token is bound to this visitor and no one else. Resolve the requester's session identifier from a session cookie, and never fall back to a shared placeholder, or every session-less visitor would share one token binding.

Bun.CSRF example: generate and verify

// 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

Bun.CSRF.generate() example with options

// 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() example with options

// 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 });

Bun.CSRF with Bun.serve() complete example

const SECRET = process.env.CSRF_SECRET || "my-secret"; function getSessionId(req: Request): string | null { return req.headers.get("cookie")?.match(/(?:^|;\s*)session=([^;]+)/)?.[1] ?? null; } const server = Bun.serve({ routes: { "/form": req => { 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}`);

Give your agent this brain