← Writing
boxlang authentication bx-express

BoxLang Express 0.2.27, and sign-in with boxlang-express-auth

BoxLang Express 0.2.27 adds page layouts and partials, regex route params, schema validation, content negotiation, signed cookies, request timeouts and body limits, an access log, cron schedules, and middleware for WebSocket upgrades. Alongside it comes boxlang-express-auth: sign-in with GitHub, Google, Microsoft, GitLab, Apple or any OpenID Connect provider, plus account linking, logout at the identity provider, and a test provider for your own specs.

BoxLang Express 0.2.27 is the biggest release since the project started. Most of it fills in parts of Express that you used to have to write yourself: page layouts, request validation, content negotiation, signed cookies, cron schedules and request timeouts. Alongside it there's a new companion module, boxlang-express-auth, which adds third-party sign-in to a BoxExpress app: GitHub, Google, Microsoft, GitLab, Apple, or any OpenID Connect provider.

This site runs on both. I upgraded it the day 0.2.27 came out, and I'll point out where it changed things here.

install-bx-module boxlang-express

Layouts and partials

Until now, every view had to include its own header and footer. Now you can name one layout for the whole app:

app.set( "views", expandPath( "./views" ) )
app.set( "view layout", "layouts/main" )

res.render() renders the view first, then renders the layout with the view's HTML in data.body:

<!-- views/layouts/main.bxm -->
<bx:output>
<!doctype html>
<html>
<head><title>#encodeForHTML( data.title ?: "My Site" )#</title></head>
<body>
	#partial( "partials/nav" )#
	<main>#data.body#</main>
</body>
</html>
</bx:output>

Because the view runs first, it can set data.title (or anything else) for the layout to read. A single render can choose another layout with { layout: "layouts/bare" }, or none with { layout: false }.

partial( view, data ) renders another view inline. It sees the caller's data plus whatever you pass it, and what you pass doesn't leak back into the page. Paths resolve from the views directory, so the ../../partials/ prefixes go away.

On this site, the head and foot includes came out of 32 views and the shared pieces (post rows, project cards, pagination, comments) became partials. One thing to know when converting: a partial sees data, not the caller's local variables. A loop variable has to be passed in, and the partial reads it as data.post.

Path patterns

A route param can now carry a regular expression, and a segment can mix params with literal text:

app.get( "/users/:id(\d+)", showUserById )     // /users/42
app.get( "/users/:name", showUserByName )       // /users/ada
app.get( "/flights/:from-:to", showFlight )     // /flights/LAX-JFK
app.get( "/assets/*rest", serveAsset )          // req.params.rest = "css/site.css"

A request that doesn't fit the pattern just doesn't match that route, so a more general route can follow it. The post URLs here are now /posts/:year(\d{4})/:month(\d{1,2})/:slug, which turned /posts/abcd/03/... from a 500 into a 404.

Request validation

boxExpressValidate() checks req.body, req.query and req.params against a schema before the handler runs. It converts values to the types you declare, fills in defaults, and answers a 400 that lists every problem:

app.post( "/users",
	boxExpressJSON(),
	boxExpressValidate( {
		body: {
			email: { type: "email", required: true },
			name : { type: "string", required: true, trim: true, maxLength: 80 },
			role : { type: "string", oneOf: [ "admin", "member" ], default: "member" }
		}
	} ),
	( req, res ) => res.status( 201 ).json( users.create( req.valid.body ) )
)

req.valid.body holds only the fields the schema names, so a client that adds "isAdmin": true to its JSON doesn't get it into your model. onError lets you answer in your own format. The admin here uses that to send the { error: "..." } shape its React client already expects.

Content negotiation and response helpers

req.accepts(), req.acceptsLanguages() and req.is() follow the npm negotiator and type-is rules. res.format() does the usual switch for you:

app.use( ( req, res ) => {
	res.status( 404 ).format( [
		html   : () => res.render( "404" ),
		json   : () => res.json( { error: "Not found." } ),
		default: () => res.type( "text/plain" ).send( "Not found." )
	] )
} )

That's close to this site's own 404 handler now. Use an ordered struct ([ ... ]): a client with no preference gets the first entry, and a plain struct doesn't keep its keys in order.

There's a batch of smaller helpers too:

  • res.get(), res.append() and res.set( { ... } ) for several headers at once.
  • res.vary(), which adds to Vary instead of replacing it.
  • res.location(), res.links() and res.attachment().
  • res.clearCookie(), and domain/expires options on res.cookie().
  • req.xhr, req.subdomains, and req.baseUrl, which tells a mounted router where it was mounted.

Signed cookies

Set a secret, then sign a cookie, and a value a user edited reads as false when it comes back:

app.set( "cookie secret", getSystemSetting( "COOKIE_SECRET" ) )

res.cookie( "plan", "pro", { signed: true } )
var plan = req.signedCookies.plan ?: "free"

Pass an array of secrets to rotate: the first one signs and all of them verify. The format matches Express's cookie-parser byte for byte, so an Express app with the same secret can read these cookies. Signed isn't encrypted, so don't put anything secret in one.

Timeouts and size limits

Five settings now bound what one client can cost the server:

app.set( "requestTimeoutMs", 30000 )   // 503 if a handler hasn't started answering
app.set( "maxBodySize", 1048576 )      // 413 for a larger body, checked before any handler

Both are off by default. When a request times out, its handler's thread is interrupted, so a stuck query or HTTP call unwinds. A response that has already started (an SSE stream, a file download) is never cut off. req.setTimeout( ms ) gives one route longer. This site gives its media moves two minutes, because a timeout between moving a file and rewriting the posts that link to it would leave broken links.

Two limits are now on by default: a client gets 60 seconds to finish sending its headers, and headers are capped at 64 KB. Before, a client that never finished its headers was held open indefinitely.

An access log that says how it went

The default log line is printed when a request arrives, so it can't tell you the status or how long the request took. app.set( "log", "access" ) prints the line when the request is answered instead:

[2026-11-15 18:12:53] GET /posts 200 86.32ms 19743b 2600:1700:…

"json" prints one JSON object per line for a log collector, and a function receives each entry to send wherever you like. Query strings stay out of it, since they carry tokens and search terms often enough.

Cron schedules

app.schedule() takes a cron expression as well as an interval:

app.schedule( "0 2 * * *", () => purgeOldUploads(), { name: "nightly-purge" } )
app.schedule( "*/15 9-17 * * MON-FRI", () => syncInventory(), { timezone: "America/New_York" } )

It supports five fields or six with seconds, ranges, lists, steps, month and weekday names, @daily and friends, and a timezone option. Every scheduled task on this site moved to cron in the same afternoon. That included a request-log flusher that had been running on a hand-rolled Java executor, so it now gets the scheduler's stall detection like everything else.

Webhooks, WebSockets and the rest

  • Text and raw bodies. boxExpressText() and boxExpressRaw() join the JSON and urlencoded parsers. All four take a type option and a verify( req, res, bytes ) hook that sees the exact bytes before they're parsed, which is what a Stripe or GitHub webhook signature check needs.
  • WebSocket upgrades can run middleware. app.ws( "/chat", handler, { use: [ sessions, requireUser ] } ) runs ordinary middleware against the upgrade request. A middleware that sends a response refuses the socket. You no longer have to re-read the session cookie by hand to find out who's connecting. connection.sendBinary() sends binary frames.
  • One MIME table. res.sendFile() and the static file handler used to disagree about types like .avif, .webmanifest and .csv. They share a single table now.

Upgrading

Most apps upgrade without changes, but check these:

  • layout is now a reserved key in render data.
  • A literal colon inside a path segment (/time/12:30) now starts a param.
  • Headers over 64 KB get a 400. Raise maxHeaderSize if you send very large ones.
  • boxExpressCors() now calls res.vary(), so a hand-written fake res in a unit test needs a vary() method.

The full docs are updated for 0.2.27, including new pages on request validation and timeouts and size limits.

Introducing boxlang-express-auth

Third-party login comes up in nearly every app, and it's easy to get subtly wrong. boxlang-express-auth handles it for BoxExpress apps. It has a generic OAuth2 core, a generic OpenID Connect provider, and presets for GitHub, Google, Microsoft, GitLab and Apple. The OIDC provider also covers self-hosted identity providers like Keycloak and Authelia. Version 0.3.0 is on ForgeBox now.

box install boxlang-express-auth

Your app decides who a provider identity is. The module runs the flow, guards routes, and keeps the session honest:

auth = boxExpressAuth( {
	verify  : ( identity, tokens, req ) => users.findOrCreateFromIdentity( identity ),
	loadUser: ( id ) => users.get( id )
} )

auth.provider( "github", boxExpressAuthGitHub( {
	clientId    : getSystemSetting( "GITHUB_CLIENT_ID" ),
	clientSecret: getSystemSetting( "GITHUB_CLIENT_SECRET" ),
	callbackUrl : "https://example.com/auth/github/callback"
} ) )

app.use( boxExpressSession( { saveUninitialized: false } ) )
app.use( "/auth", auth.routes() )

app.get( "/dashboard", auth.required(), ( req, res ) => res.json( { user: req.user } ) )

Link to /auth/github and you're done. auth.required() redirects an anonymous browser to your login page and answers an API client with a 401. auth.optional() sets req.user when someone is signed in.

Providers

GitHub uses plain OAuth2. Everything else is built on the OIDC provider, so every one of them gets the same ID-token checks:

  • Google, with an optional hostedDomain to limit sign-in to one Workspace domain. It's enforced against the signed hd claim, not just the hint Google documents as removable.
  • Microsoft Entra ID, with tenant set to common, organizations, consumers or a single tenant, and allowedTenants for a multi-tenant app that only lets in the customers it has onboarded. Microsoft's multi-tenant endpoints publish a templated issuer, so the preset checks each token's iss against its own tenant id. Microsoft doesn't verify the email claim, so the preset never reports it as verified.
  • GitLab, for gitlab.com or your own instance via baseUrl.
  • Apple. Apple's ID tokens are ordinary, but everything around them isn't. The client secret is a JWT you sign with your team's .p8 key, so the provider mints a fresh one for every code exchange. Asking for a name or email makes Apple come back with a cross-site form POST, which a SameSite=Lax session cookie doesn't ride along on. The module answers that POST with a redirect to the usual GET callback, where the cookie is sent and every check runs unchanged. Apple only sends the user's name once, on the first sign-in, and the module hands it to verify() so you can save it.
  • Any OIDC issuer, such as Keycloak or Authelia, from its discovery document.

Security, done for you

  • PKCE on every login. An intercepted code is useless without the verifier held in the session.
  • state is single-use and short-lived. It's 32 random bytes, deleted before it's checked, expires after 10 minutes, and is compared in constant time.
  • The session is regenerated before the user id is written, so a planted session id can't be carried into a signed-in session.
  • ID tokens are fully validated: the signature against the issuer's keys (RS256/384/512 and, new in 0.3.0, ES256/384/512; none and HMAC refused), plus issuer, audience, expiry and nonce.
  • Provider tokens are never stored or logged. They're handed to verify() and dropped, so if you need one later, you store it yourself.
  • No GET logout. A link or an <img> on another site can't sign your users out.

Signing out everywhere

For single sign-on, ending your app's session isn't enough: the user is still signed in at Keycloak or Microsoft, and the next login goes straight through. Give an OIDC provider a postLogoutRedirectUrl, and POST /auth/logout destroys the local session and then sends the browser on to the issuer's own logout. A form post gets a redirect, and a fetch() gets { logoutUrl }.

Linking accounts

The README says to key users on the provider's own id and never on email, because an address can be unverified, reassigned, or typed into another provider by someone else. That leaves the question of how someone adds a second provider to their account. 0.3.0 answers it with a link() option:

auth = boxExpressAuth( {
	verify  : ...,
	loadUser: ...,
	link    : ( identity, user, tokens, req ) => {
		var owner = identities.find( identity.provider, identity.id )
		if ( !isNull( owner ) && owner.userId != user.id ) {
			return false                 // already someone else's
		}
		identities.attach( user.id, identity )
		return true
	}
} )

A signed-in user posts a form to /auth/google/link, goes through the same flow and checks as a login, and link() gets the new identity together with the user who is already signed in. It's POST-only so it sits behind your CSRF protection. It's refused if a different user is signed in by the time the provider sends them back.

Testing your app

boxExpressAuthTestProvider() signs a user in through the real /auth routes, including state, PKCE, your verify() and the session regeneration, with no provider account and no network:

testLogin = boxExpressAuthTestProvider( { identity: { id: "u1", email: "[email protected]" } } )
auth.provider( "test", testLogin )      // only when building the app for tests

var login = testLogin.login( app )
expect( app.inject( { url: "/dashboard", cookies: login.cookies } ).statusCode ).toBe( 200 )

testLogin.login( app, { deny: "access_denied" } )     // the user clicked Cancel
testLogin.login( app, { fail: "profile_failed" } )    // the provider broke

Even if you register it by mistake, it can't sign anyone in from a browser: its authorize URL never resolves, and a code only exists once test code approves one.

WebSockets

With BoxExpress 0.2.27's upgrade middleware, the same guard protects a socket:

app.ws( "/chat", handler, { use: [ sessions, auth.required() ] } )

An anonymous upgrade gets a plain 401, never a login redirect.

On this site

This site uses it for "Sign in with Google" and "Sign in with GitHub", both for commenters and for the admin, where a passkey is still required on top. It replaced the two OAuth client classes I'd written myself, close to 300 lines between them, and the module checks more than they did.

boxlang-express is on GitHub and ForgeBox, and boxlang-express-auth is on GitHub and ForgeBox. Issues and pull requests are welcome on both.

No comments yet — be the first.