Auth and sessions
Mechanics, not policy: borgo gives you signed-cookie sessions, password hashing behind a swappable interface, ready-made login/logout/register handlers over a user provider you supply, a hook that is told what those handlers saw, guards for both sides of the bridge, and CSRF protection for form actions and for browser calls that change something through /api/*. It imposes no database, no user schema, and no OAuth opinion — those stay in your hands.
The complete flow — register, login, protected page, logout — is wired in examples/tasks (api/users.go, pages/login.tsx, pages/register.tsx, pages/account.tsx).
Sessions#
Sessions are a JSON payload HMAC-signed with SESSION_SECRET, stored in an http-only cookie — no server-side storage, expiry signed in. Behind https set SESSION_SECURE=1 (or true; the grammar is Go's strconv.ParseBool, case-sensitive, and a value it cannot read — yes, on — stops the boot rather than issuing an insecure cookie):
type Session struct{ User string `json:"user"` }
borgo.SetSession(w, Session{User: user}, 24*time.Hour)
session, ok := borgo.GetSession[Session](r) // false when missing, tampered or expired
borgo.ClearSession(w) // logout
The render service forwards the browser's cookies on every api call a loader or action makes, so Go sees the session during SSR — and forwards Set-Cookie headers coming back from Go to the browser, so an action that calls a login route actually logs the browser in. A cookie Go sets is also carried by the later calls of the same loader or action, so an action that registers and then saves something does both as the new user.
Four behaviors worth knowing before you design around them:
- An absent
SESSION_SECRETis warned about, a short one is refused. With none set, borgo boots anyway, because an app with no sessions is a legitimate app, and logsborgo: SESSION_SECRET not set (or under 32 bytes): sessions and auth refuse until it isonce, at the first request that carries a session cookie or tries to set one. The failure is per request and closed in both directions:/healthzstays green whileSetSessionreturnsErrNoSessionSecret, login and register answer500 {"error":"session write failed"}, and no session verifies — so nothing can be forged against the missing key. With a secret shorter than 32 bytes,Servestops instead of starting: that length is searchable offline from one captured cookie, and the rest of the framework treats such a value as no secret at all. Watch for that line on the first login; it is the only warning there is. - The principal rides in the cookie, so keep it small — a username, an id, a role.
SetSessionreturns an error rather than writing a cookie the browser would silently drop for exceeding 4 KB, and that error is worth surfacing: a dropped cookie looks exactly like a successful login that did not stick. - Logging in replaces any existing session, so a session fixed on a victim before login cannot survive it.
- Two valid
borgo_sessioncookies are treated as none, whatever their values. A sibling subdomain can plant a duplicate; guessing which one to trust is how an attacker chooses your session for you. See security.
Revoking sessions#
A signed cookie is valid until it expires, unless the app says otherwise. borgo.CheckSession registers one check that Go runs on every session whose signature and expiry verified, before anything reads it: GetSession, borgo.Authed, and the session the front hands the render service for loaders and middleware.ts. Answer false and the request has no session. The cookie is not rewritten, so a revocation takes effect on the next request — and so does lifting one. A WebSocket or an event stream already open is not a request: it was judged at its handshake and keeps its topics until it closes, so tell it to go yourself if that is too late, as examples/tasks does with a push on the user's own topic.
The cheapest revocation needs no session store, because every session records when it was issued: "log me out everywhere" is one timestamp per user.
// when each user last asked to be logged out everywhere
var revokedBefore sync.Map // username -> time.Time
func init() {
borgo.CheckSession(func(r *http.Request, s borgo.SessionInfo) bool {
var me Me
if json.Unmarshal(s.Data, &me) != nil {
return false
}
cutoff, revoked := revokedBefore.Load(me.Username)
return !revoked || s.IssuedAt.After(cutoff.(time.Time))
})
}
func logoutEverywhere(w http.ResponseWriter, r *http.Request) {
me, ok := borgo.GetSession[Me](r)
if !ok {
borgo.Error(w, http.StatusUnauthorized, map[string]string{"error": "unauthenticated"})
return
}
revokedBefore.Store(me.Username, time.Now())
borgo.ClearSession(w)
w.WriteHeader(http.StatusNoContent)
}
The same shape takes a role away: store the moment it changed, and every session issued before it stops working on its next request instead of at its expiry.
- It runs once per request under
borgo.Serve, however many times the request reads the session: the app's middleware, the handler and the hand-off to the render service share one answer, so a check that queries a database queries it once. An embedder callingGetSessionon its own server runs the check on every read. - A panic is no session, logged with its stack. A revocation store that is down does not hand revoked sessions back.
IssuedAtis to the millisecond. A session written by a borgo before 0.30 carries no issue time and reads as the Unix epoch, so any cutoff revokes it.- Inside the check,
GetSessionanswers with the session being checked, unchecked, rather than recursing into the check;s.Datais the same bytes. - The map above is per process. Behind several instances the cutoffs belong in a store they share, or a revocation holds only on the instance that recorded it.
Register the check in init(), beside your routes: after Serve it panics, as a late route does. Without a check nothing changes and nothing is paid.
A session that lasts while it is used#
A session lasts for the maxAge it was written with, counted from the sign-in: seven days later, somebody in the middle of their work is signed out. borgo.RenewSession is the other policy — a session that stays alive while somebody is using it and ends a fixed time after they stop. When the session the request carries was issued more than olderThan ago, it writes the session again, to last maxAge from that moment, and it reports whether it wrote one. Call it from api/middleware.go, before the handler:
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// an hour old or more: written again, to end eight hours from now
borgo.RenewSession[Me](w, r, time.Hour, 8*time.Hour)
next.ServeHTTP(w, r)
})
}
maxAge is the idle timeout. olderThan is how often a cookie is written: long enough that not every response carries a Set-Cookie, and well under maxAge, so that a session cannot run out between two renewals. Give Auth.MaxAge the same eight hours, or the first session outlives the policy.
Tis the whole session. The session is decoded intoTand written back from it, so a fieldTdoes not declare is gone after the first renewal. Use the type yourPrincipalreturns.- A renewal is a new session. Its
IssuedAtis the moment of the renewal, so a revocation cutoff still works, and a limit on the time since sign-in needs that time stored in the session data: nothing else remembers it. - A session
CheckSessionrefuses is not renewed. It is not read at all. - It signs with the current key. After a key rotation the sessions in use move to the new key on their own, one renewal each.
- It has to run before the response starts, since it sets a cookie. A session that cannot be written — no
SESSION_SECRET, a cookie over 4 KB — is logged and reported asfalse.
A session that did not come in a cookie#
An api that scripts and other services call is opened with a token in a header, and its handlers are the ones your pages use: they ask GetSession who is calling. borgo.WithSession lets api/middleware.go answer that for a request it has authenticated its own way.
// whose token the Authorization header carries: a lookup of your own,
// against the hashes you keep
func lookupToken(r *http.Request) (Me, bool) {
return Me{}, false
}
func Tokens(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
bot, found := lookupToken(r)
if !found {
http.Error(w, "unknown token", http.StatusUnauthorized)
return
}
// every handler behind reads bot from GetSession
r = borgo.WithSession(r, bot)
}
next.ServeHTTP(w, r)
})
}
- The claim is yours. borgo checks no signature and does not ask
CheckSession: call it only once you know who this is. Store a hash of each token, never the token, and compare in constant time. - It is that request's alone. No cookie is written, and the next request is asked again.
- It comes before the cookie. A request that carries both a token and a session cookie is the token's.
- A token request needs no CSRF token. The check is for requests a browser sends with cookies it attached by itself; a client that sends no cookie is not one of those.
- Use the type your handlers read. The value is encoded as JSON and decoded by
GetSession[T], as a cookie's session is.
Password hashing#
borgo.DefaultHasher() returns PBKDF2-HMAC-SHA256 with OWASP parameters (600,000 iterations, 16-byte random salt), from the standard library's crypto/pbkdf2. The choice, honestly: argon2id is the state of the art, but it lives in golang.org/x/crypto, and the Go runtime's zero-dependency guarantee is part of what borgo is. PBKDF2 at these parameters is an OWASP-recommended configuration and FIPS-approved; if your threat model wants argon2id, the hasher is one small interface away:
type PasswordHasher interface {
Hash(password string) (string, error)
Verify(password, hash string) bool
}
Set Auth.Hasher to your own implementation and nothing else changes. Hashes embed their parameters (pbkdf2$600000$<salt>$<key>), so stored passwords keep verifying if defaults evolve — within bounds: a stored hash asking for parameters far beyond the defaults is rejected outright, because deriving the key it demands is minutes of CPU per attempt.
Verifying is not replacing: a hash made with yesterday's parameters keeps yesterday's cost until somebody stores a new one, and the only moment the password is known is a sign-in. Auth.Rehash is for that moment. When the stored hash verifies and the hasher says it is out of date, LoginHandler hashes the verified password afresh and hands the new hash to your function:
// saveHash stands for an update of the user's row
func saveHash(ctx context.Context, username, hash string) error { return nil }
var rehashing = borgo.Auth[User]{
Lookup: lookupUser,
Rehash: saveHash,
}
"Out of date" is for the hasher to say. A hasher that also has NeedsRehash(hash string) bool — the borgo.Rehasher interface — is asked, and the default one answers true for a PBKDF2 hash with fewer iterations than it uses today, and false for anything that is not a PBKDF2 hash, which is not its to judge. A hasher of your own that verifies two formats, the one you are leaving and the one you are moving to, says true for the old one and the table migrates as people sign in. Without Rehash old hashes keep verifying and are never replaced. An error from Rehash is logged and the sign-in stands: the old hash is still there, and still right. The second hash runs in the same slot as the verification, so a migration does not raise the number of hashes running at once.
Hashing is deliberately expensive, which makes it a resource to protect. LoginHandler runs at most max(1, GOMAXPROCS/2) verifications at once — BORGO_HASH_SLOTS overrides that, read once at package init — and sheds the rest with 503 and a Retry-After after five seconds of queueing, so a burst of login attempts cannot starve every other route on the server. A failed lookup still runs a verification against a dummy hash — one built with your hasher, so swapping in argon2id does not reintroduce a timing oracle — which keeps "no such user" and "wrong password" indistinguishable in both the response and the clock.
The cap only covers the hashes borgo runs. A handler of your own that hashes — a password change, which verifies the old one and hashes the new — sits outside it unless it takes a slot too, and that is what borgo.WithHashSlot is for:
func passwordMatches(w http.ResponseWriter, r *http.Request, current, stored string) (matches, answered bool) {
if !borgo.WithHashSlot(w, r, func() {
matches = borgo.DefaultHasher().Verify(current, stored)
}) {
return false, true // shed with a 503, or the client is gone
}
return matches, false
}
One slot per hash, taken and released around it: holding a slot across a database call would spend the cap on waiting.
borgo.Auth: login, logout, register#
borgo.Auth[U] turns a user provider into handlers. You supply Lookup (and optionally Register); the framework does the verification, the hashing, and the session:
var auth = borgo.Auth[User]{
// username -> user + stored password hash. any error answers 401.
Lookup: func(ctx context.Context, username string) (User, string, error) {
var user User
err := db.DB.First(&user, "username = ?", username).Error
return user, user.Hash, err
},
// optional: creates the user from an already-hashed password.
// return borgo.ErrUserExists for a taken username -> 409.
Register: func(ctx context.Context, username, hash string) (User, error) {
user := User{Username: username, Hash: hash}
return user, db.DB.Create(&user).Error
},
// what the session stores - keep it minimal, it rides in a cookie
Principal: func(u User) any { return Me{Username: u.Username} },
}
func init() {
borgo.Handle("POST /api/login", auth.LoginHandler)
borgo.Handle("POST /api/logout", auth.LogoutHandler)
borgo.Handle("POST /api/register", auth.RegisterHandler)
}
LoginHandlerdecodes{username, password}(borgo.Credentials), verifies against the stored hash, starts the session and responds with the principal as JSON. Empty fields are a 400 before any lookup; wrong password and unknown user are both a 401{"error": "invalid credentials"}— and a failed lookup still runs a hash verification, so usernames cannot be enumerated by timing. An address that fails ten times in a minute is answered429withRetry-Afteruntil the minute is over, before its body is read:BORGO_LOGIN_ATTEMPTSchanges the number, and rate limiting says what that does and does not cover. Since 1.1 an IPv6 address is counted by its /64: one customer line holds a whole /64, and counted address by address it had as many allowances as it cared to use.RegisterHandlerhashes the password, callsRegister, starts the session, responds 201.borgo.ErrUserExistsbecomes a 409; with noRegisterconfigured the route answers 404.LogoutHandlerclears the cookie, responds 204.
These handlers can report what they see: set OnEvent on the Auth and it is called for every sign-in, failed sign-in, sign-in refused by the limit, sign-out and new account, with the kind, the username as typed, the client's address and the time. It is where an audit log or a "new sign-in" mail starts; security has the kinds and the rules.
These routes are typed like the ones you write. Principal returns any, so the type is not in its signature; borgogen reads it where it is, in the source: the Auth declared as a package-level literal, and the values its Principal returns — or the user type itself when there is no Principal. api("POST /api/login", ...) then resolves to that shape, a union when Principal returns more than one type, and takes borgo.Credentials as its body. Where the source does not say, the response stays unknown rather than being guessed. That is when the Auth is built by a function or is exported, a return is already an interface, or the value is used in any way that could change its Principal - assigned to, copied, its address kept or handed to a function of yours. Keep it an unexported package-level var. Mounting its handlers and passing it to borgo.Signup are fine: those uses are read.
A signup form of your own shape: borgo.Signup#
RegisterHandler takes {username, password} and nothing else, and no signup form anybody ships stops there. borgo.Signup is the same handler over a body of your own: any struct that embeds borgo.Credentials, so the framework finds the username and the password, and the rest is yours. It is decoded as borgo.Bind decodes it, and handed to your function beside the hash of its password. Set Principal: without it the whole user is the session and the body of the login and register responses, hash included - signed, not encrypted, and readable by the browser:
type Account struct{ Username, Email, Hash string }
// what the session holds and the login answers with: never the hash
type AccountSession struct {
Username string `json:"username"`
}
type SignupBody struct {
borgo.Credentials
Email string `json:"email"`
}
var accounts = borgo.Auth[Account]{
Lookup: func(ctx context.Context, username string) (Account, string, error) {
a, err := findAccount(ctx, username)
return a, a.Hash, err
},
Principal: func(a Account) any { return AccountSession{Username: a.Username} },
}
// the form reaches register whole; the password reaches it hashed
func register(ctx context.Context, form SignupBody, hash string) (Account, error) {
a := Account{Username: form.Username, Email: form.Email, Hash: hash}
return a, saveAccount(ctx, a)
}
func init() {
borgo.Handle("POST /api/register", borgo.Signup(&accounts, register))
}
// your store
func findAccount(ctx context.Context, username string) (Account, error) { return Account{}, nil }
func saveAccount(ctx context.Context, a Account) error { return nil }
The answers are RegisterHandler's, which is Signup over Credentials alone: an empty username or password is a 400 before any hashing, ErrUserExists a 409, a missing SESSION_SECRET a 500 before the store is written, too many parallel hashes a 503 with Retry-After; on success the session starts and the principal comes back with a 201. What the app validates beyond that it answers in its own words. Give the form a Validate() error method and it is asked before the password is hashed, so a refused form costs no PBKDF2; return borgo.Refuse(status, body) - from Validate, or from your register function for an email already registered - and that status and JSON body are the answer, field and all. Any other error from Validate is a 400 with its message; any other from register is a 500 registration failed. The typed bridge reads the form as the route's request type, so a misspelled field in api("POST /api/register", { body }) fails tsc. Embedding by value is the way in, deliberately: a form that spelled its own password field would leave the framework hashing nothing, and a form that reaches Credentials through a pointer or an interface is refused when Signup is built, since a body of null would leave it nothing to call. A form holding a borgo.File is refused there too, and by borgogen: the body is JSON, which carries no upload, only fields the client wrote, so take an avatar in a route of its own that reads it with borgo.BindMultipart.
Defaults: 7-day sessions (MaxAge), DefaultHasher() (Hasher), the user itself as principal (Principal), no Rehash and no OnEvent. The first three are fields, not policy — and Hasher is the only way to change hashing, deliberately: DefaultHasher is a function, so no code in the process can reassign the default out from under an Auth that did not ask for it.
Guarding api routes: borgo.Authed#
borgo.Handle("GET /api/me", borgo.Authed(currentUser))
Without a valid session the request is answered 401 {"error": "unauthenticated"} and the handler never runs. borgogen sees through the wrapper, so the route keeps its generated TypeScript types. Need the principal inside the handler? borgo.GetSession[Me](r) as usual — Authed only checks validity, it does not impose a session type.
For anything beyond a boolean gate (roles, ownership), write the three-line wrapper yourself — handlers are ordinary http.HandlerFuncs — or put the rule in api/middleware.go once, in front of every route its matcher covers:
func admin(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s, ok := borgo.GetSession[Me](r); !ok || s.Role != "admin" {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
h(w, r)
}
}
Guarding pages: middleware.ts#
The pattern for protected pages is middleware.ts at the root of the app: one file that runs before the document, the props of a client navigation and the form actions of every page its matcher covers, with the session Go already verified. Middleware and authorization has all of it:
import { next, redirect, type PageMiddleware } from "borgo-framework";
export const matcher = ["/account"];
export const middleware: PageMiddleware = (_request, { session }) => (session ? next() : redirect("/login"));
A loader receives the same verified session, so a rule only one page has can still live in its loader:
import { redirect, type LoaderContext } from "borgo-framework";
export async function loader({ session, api }: LoaderContext) {
if (!session) return redirect("/login");
return { tasks: await api("GET /api/tasks") };
}
A guard in a loader covers that loader and nothing else: the page's action needs a check of its own, which is the gap middleware.ts closes. The data stays guarded where it lives either way — borgo.Authed or api/middleware.go answers the api call, from a loader or from a browser.
Login and logout as form actions#
Form actions work without client JavaScript, and Set-Cookie forwarding makes them the natural login flow:
import { ApiError, redirect, type ActionContext } from "borgo-framework";
export async function action({ request, api }: ActionContext) {
const form = await request.formData();
try {
await api("POST /api/login", {
// a form field may be a file: the route takes strings, and its type says so
body: { username: String(form.get("username") ?? ""), password: String(form.get("password") ?? "") },
});
} catch (error) {
if (error instanceof ApiError && error.status === 401) return { error: "wrong username or password" };
throw error;
}
return redirect("/account");
}
Go sets the session cookie on the api response; the render service forwards it on the action's redirect; the browser lands on /account logged in. Logout is the same shape: an action calling POST /api/logout, a redirect, done.
CSRF protection for actions and api calls#
Every <form method="post"> needs <CsrfField /> inside it:
import { CsrfField } from "borgo-framework";
export default function NewTask() {
return (
<form method="post">
<CsrfField />
<input name="title" />
<button>Add</button>
</form>
);
}
The render service issues a borgo_csrf cookie with the page, the field carries the same token back, and a mismatch is answered 403 before the action runs — a cross-site form cannot read the cookie, so it cannot produce the field. The check arms for any browser that holds the token, which is what closes login-CSRF; cookie-less clients are unaffected.
That covers forms. The other half of the obligation is browser calls to /api/* that change something — POST, PUT, PATCH, DELETE — which carry the same token in an X-CSRF-Token header instead of a field, because an api body is JSON and has no field to put it in. Use apiFetch and it is attached for you - and use it from the start: the check is off under borgo dev unless BORGO_CSRF=1, so a bare fetch works until the first deploy:
import { apiFetch } from "borgo-framework";
await apiFetch("/api/logout", { method: "POST" });
A loader or an action calling api("POST /api/logout") needs nothing: that client calls the api's internal listener, and the header check guards the public port, not that listener. Security has the exact scope, the mechanics and the environment overrides.
What the framework protects, and what you still owe#
borgo gives you the mechanics. These remain your decisions, and none of them are hard — but nothing here will do them for you:
- Password policy. Nothing enforces a minimum length or checks a breach list.
DefaultHasher()makes a weak password expensive to crack, not safe. - Lockout, and limits on anything but sign-in.
LoginHandlercounts failures by address — ten a minute,BORGO_LOGIN_ATTEMPTS— and answers429past them, which slows one address guessing at any account. It does not count per account, on purpose: that is a way for anybody to lock somebody else out. A guesser with many addresses is a matter for your proxy or your own store —OnEventis where such a store hears of each failure — and every other route is limited only if you say so:borgo.Limiton the route, or the recipe in rate limiting. - Registration abuse. No email verification, no captcha, no duplicate-signup throttling.
RegisterHandleranswers409on a taken username, which is an existence oracle you accept in exchange for a usable signup form — mask it if your threat model cannot. - Password reset, email change, 2FA, OAuth, SSO. All absent by design. They are product decisions with wildly different answers per app, and each needs a channel (email, TOTP, an identity provider) that borgo has no business owning. Recipes has a reset built from the pieces that are here.
- Session revocation is a check you write. Sessions are self-contained signed cookies, so borgo keeps no list to delete from: without
CheckSessiona stolen cookie is valid until it expires. The check is where you choose what revocation costs — a map, a cache, a query. ReplacingSESSION_SECRETstill logs everyone out at once, unless the old key is listed inSESSION_SECRET_PREVIOUS, which is how a key is rotated without signing anyone out.
The trade that buys: no session store, no lookup per request, and a server that can be restarted or replicated without anybody being logged out.
Caching#
Not auth, but usually decided together: borgo.Cache(w, 5*time.Minute) for anything public, borgo.NoCache(w) for anything personalized — see caching in the deploy guide. A response that carries Set-Cookie is made private whichever order the handler calls the two in: Cache checks for a cookie as it runs, and SetSession/ClearSession run the same guard, as does the middleware borgo.Serve installs when the headers commit. The order only matters on a mux borgo does not own — wrap it in borgo.Middleware and the guarantee comes with it.