LuxelEspañol

Luxel v0.1 · Guide · part 1 of 2

Sessions

Sessions are the framework's job. Your handlers say who signs in (ctx.signIn) and when a session ends (ctx.signOut). They never read or write a cookie. This page covers where sessions are kept, sign-in and sign-out, static public views (a sign-in page without a session), rate limits, the replay guard, and running several nodes.

How a session works

  • The session id is 256 random bits. It lives only in an HttpOnly, Secure, SameSite=Strict cookie named __Host-luxel_session. The __Host- prefix makes the browser require Secure and Path=/ and forbid a Domain attribute, so a sibling subdomain cannot set it.
  • The id is never stored. A store keeps a hash of it.
  • The CSRF token is derived from the id (another hash). No store keeps it; it is the same on every node, and a new id gives a new token.
  • Signing in rotates the id: the previous one stops resolving (no session fixation).
  • Logout and revocation happen in the store, so with a shared store every node refuses the session on its next request. Expiry is checked on every request.
  • Default lifetimes: 30 minutes for an anonymous session, 8 hours for a signed-in one.

The three session stores

Export one from server/bindings.mjs as sessionStore.

Memory: one process

import { createMemorySessionStore } from '@luxel-framework/gateway'; export const sessionStore = createMemorySessionStore();

Use it for development and for a single node. A restart of luxel-host signs everyone out (under luxel dev a session survives the host restart a server edit causes: see Tooling). It is not shared, so the host refuses LUXEL_NODES above 1 with it in production. It keeps at most 50 000 live sessions by default (maxSessions) and sweeps expired ones itself. Lifetimes can be changed with { lifetimes: { anonymousMs, authenticatedMs } }.

PostgreSQL: several nodes, or restarts that keep sessions

import pg from 'pg'; import { createPgSessionStore } from '@luxel-framework/postgres'; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); export const sessionStore = createPgSessionStore({ pool });

One table (luxel_session by default; table changes it), created at start-up under an advisory lock so several nodes can start at once. Logout, revocation and expiry are rows deleted or filtered. createPgSessionStore takes any pool with query(text, values), such as node-postgres' Pool.

create-luxel does not add @luxel-framework/postgres or pg to a new app. Install them yourself; until Luxel is on npm, the adapter comes from the packed tarball:

npm install ‹path-to-luxel>/.packs/luxel-framework-postgres-‹version>.tgz pg

Delegated: your backend owns sessions

When an existing backend already keeps sessions (for example a JWT it issued), luxel-host can keep nothing and ask the backend:

import { createDelegatedSessionStore, httpSessionDelegate } from '@luxel-framework/gateway'; export const sessionStore = createDelegatedSessionStore( httpSessionDelegate({ url: process.env.SESSION_BACKEND_URL, secret: process.env.SESSION_BACKEND_SECRET }), );

The backend implements five operations, each keyed by the hash luxel-host sends (it never sees the session id or the cookie): open, validate, revoke, revoke-user, purge. httpSessionDelegate calls them as POST ‹url>/‹op> with a JSON body and Authorization: Bearer ‹secret>, server to server. The backend decides whether a session is still valid; luxel-host checks the expiry too. You can also pass your own SessionDelegate object instead of the HTTP one.

Which one

SituationStore
Development, tests, one node where a restart may sign people outMemory
Several nodes, or sessions that survive restartsPostgreSQL
An existing backend keeps and revokes its own sessionsDelegated

Sign-in: ctx.signIn

export const login = defineEvent(events.sessionLogin, async ({ username, password }, ctx) => { if (username.trim() === '' || password === '') return ctx.reject('VALIDATION', ctx.message('missing')); const user = await checkCredentials(username, password); if (!user) return ctx.reject('VALIDATION', ctx.message('invalid')); return ctx.signIn({ userId: user.id, roles: ['user'], displayName: user.name }).navigate('contacts'); });

After the answer, the framework opens a new session (new id, new CSRF token), drops the session the request carried if any, and sets the cookie. The handler checks the credentials; the framework handles everything about the session.

What the template does that you should keep:

  • one message for an unknown user and a wrong password;
  • the same work in both cases (it runs scrypt against a dummy hash for an unknown user), so neither the answer nor its time tells who exists.

The framework cannot enforce these for an arbitrary handler: they are yours.

The sign-in event is publicEvent(), or anyone() in a screen file. In the template it is anyone({ effect: 'read' }): it reads the user store and changes no business data.

displayName is kept by the session store and is never a secret. Handlers see ctx.session as { id, userId, roles } only: to show a name, read it from your user store by userId in the load.

Sign-out

Three ways. Each ends the session in the store (on every node) and clears the cookie.

  • ‹Logout>, a sign-out button that needs no JavaScript:

import { Logout } from '@luxel-framework/ui'; ‹Logout to="login" className="button">Sign out‹/Logout>

The compiler writes a form of its own, ‹form method="post" action="/_luxel/logout"> with one submit button. The browser submits it; the server ends the session and answers 303 to the page of to. With the runtime loaded it works the same way: the runtime leaves this form to the browser.

  • to is a public view of the app (public: true), fixed when you build; without it, the view's loginView (login by default). The visitor has no session when they arrive, so a private view or a page is refused (LUXEL-E066): the host would only redirect it to its own loginView. The form does not carry it: the build writes the address into the host's config (logout: "/‹variant>/‹view>", the variant of home), and the answer never reads where to go from the request. So an app has one destination: every ‹Logout> names the same one, a route served in the variant of home, or the build stops (LUXEL-E066). If that view has a path (Routes), the address in the config is still its id address; the host answers it with a redirect to the path, like any id address of a view with a path.
  • The form holds no token and nothing of the session, so the view's template stays public and the same for everyone. What the server asks of the request instead is in Security.
  • It is a text zone (id, default logout), styled with className (the button's). It cannot be inside a form (as="form") or in a collection's item template, and it exists only in filled pages (variants with projection: 'slots'): a view served in another kind of variant signs out with an event (LUXEL-E066 says so).
  • It needs sessionStore in the bindings (the host does not start without one).
  • For policies.allowedComponents, luxel check counts it as Logout, not as a Text: a policy that sets the list must name 'Logout' to allow it (LUXEL-E035 otherwise). Without the policy every component is allowed.
  • An event, when signing out has something else to do (the handler runs first):

export const logout = defineEvent(events.sessionLogout, async (_input, ctx) => ctx.signOut().navigate('login'));

In a screen file: signOut: s.event({ policy: allow(USER, { effect: 'read' }) }, async (_input, ctx) => ctx.signOut().navigate(login)), sent by an ‹Action event={events.signOut}>. An event needs the runtime (JavaScript).

  • The framework route from a script POST /_luxel/logout: same origin, with the CSRF header, and the same checks as an event (rate limit, Fetch Metadata, Origin, session, CSRF). It answers 204 with the cookie cleared and Clear-Site-Data: "cache".

An administrator can end every session of a user with sessionStore.revokeUser(userId). Expired sessions are deleted by sessionStore.purgeExpired(); run it on a schedule with a shared store (the memory store sweeps itself).

Routing by session

views: { login: { public: true, static: true, identity: 'username' }, contacts: { loginView: 'login' }, },

  • loginView: where an anonymous visitor of a private view is sent.
  • public: true: the view accepts anonymous sessions.
  • whenAuthenticated: for a public (non-static) view, where a signed-in user is sent instead.

Static public views

A sign-in page shows no user data. Luxel can serve it as a static page: the same bytes for everyone, with no session before the sign-in succeeds.

login: { public: true, static: true, identity: 'username' },

  • static needs public: true and cannot be combined with whenAuthenticated (the page cannot depend on who asks). identity must name an input of the view's events. Otherwise: LUXEL-E051.
  • The host fills the page once at start-up, with what its load returns without a session (or no load at all). It serves it without reading the Cookie header, without opening a session and without Set-Cookie, as Cache-Control: public, no-cache with an ETag: any cache may store it and must revalidate it.
  • A page with anyone's data is never static.
  • Its load has no session (Sprint 11). A static view's defineLoad gets a context without session: no user, no roles, no scopes. Reading them fails the build (LUXEL-E056, also in luxel check), and at run time ctx.session throws, so the host does not start. Show only what is the same for everyone.
  • A static page is part of the build. luxel sign fills it and records its hash. If its load returns something else at start-up (the time, a database row, an edited module), a production host refuses to start.

Browsers

A static form needs Fetch Metadata (Sec-Fetch-Site). There is no session CSRF token to fall back on. Supported: Chrome and Edge 76/79 and later, Firefox 90 and later, Safari 16.4 and later. Checked in Chromium 159, Firefox 159 and WebKit 27.2 (tests/browsers, Sprint 11). An older browser gets 403 FORBIDDEN with a message that says it needs a current browser.

If your users include older browsers, keep the sign-in view non-static (drop static: true). It then gets an anonymous session and its CSRF token, and Origin and that token protect it, as before Sprint 10. That costs a session row per visit of the sign-in page. Keep identity on it: since Sprint 11 (red team RT-1) the per-address and per-account sign-in limits apply to non-static sign-in views too, and a public view whose handler calls ctx.signIn without identity gets a build warning (LUXEL-W004).

How the form is protected without a session

There is no session, so there is no session CSRF token. Instead, right before each send, the runtime asks the gateway for a form token (GET /_luxel/view/‹id>, which opens no session for a static view). The token is signed, bound to the view and its build, valid for 2 minutes, single use, and stored nowhere when issued.

The event (POST /_luxel/event) is accepted only if, in order:

  1. the general rate limit (by client address) passes;
  2. Sec-Fetch-Site: same-origin is present and Origin names this host (both required);
  3. Content-Type: application/json and the size limit;
  4. the protocol version is compatible;
  5. the body decodes against the view's manifest and the Avt header carries a token;
  6. the form token verifies (signature, view, build, key, expiry);
  7. the sign-in rate limit passes: one bucket per client address and one per account (the value of the input named by identity, trimmed and lower-cased, hashed);
  8. the replay guard claims the token's nonce: a token is used once, whatever the handler answers.

What stops a cross-site sign-in attempt is what the browser enforces: Fetch Metadata and Origin, which a page cannot forge, and the custom Avt header with a JSON content type, which a cross-origin page cannot send without a CORS preflight that the gateway never grants. The form token is not a secret (anyone can get one); it bounds time, form, integrity and replay.

Why there is no session before sign-in

  • No session row is created per visit, so the store grows only with real sign-ins.
  • There is no id to plant through the sign-in page (no fixation), and a session cookie the request carries is dropped on success, never adopted.
  • One page for everyone: a shared cache may store it, because it holds no user data.

The trade-offs: a browser without Fetch Metadata cannot sign in through a static form (see Browsers), and anyone can spend an account's sign-in bucket (10 attempts, then one every 6 seconds by default).

When someone spends an account's limit: accountLimit

The per-account limit slows down guessing a password. It also lets anyone slow down the real user, by sending wrong passwords for that account. Choose what a spent account bucket does (Sprint 11):

login: { public: true, static: true, identity: 'username', accountLimit: 'delay' },

accountLimitWhen the account's bucket is spent
'refuse' (default)429 until it refills: the real user waits too
'delay'The attempt waits for the account's next slot (at most 6 s), then goes on. The wait holds no exclusive slot (red team RT-3: an attacker with two addresses used to keep the one waiting slot and lock the victim out). The real user signs in a few seconds later
'handler'The attempt goes on, and the handler sees ctx.throttled === true: ask for a second factor or a CAPTCHA before ctx.signIn. A handler that never reads ctx.throttled fails the build (LUXEL-E057, RT-4)

The per-address limit refuses in every mode.

export const login = defineEvent(events.sessionLogin, async ({ username, password, code }, ctx) => { if (ctx.throttled && !(await secondFactorOk(username, code))) return ctx.reject('VALIDATION', ctx.message('secondFactor')); // … });

Edit this page on GitHub

This page: 7.9 KB of JavaScript (Luxel's shared runtime), 0 KB from your app.

Measured when the site is built: the runtime files this page loads, compressed as they are sent.

Made by IntiOps. Luxel 0.1.0-beta.1 is a beta: no external security review yet.