Packages

Authentication

ajo-kit-auth: sessions, CSRF, guards, tokens, teams, passkeys and more.

ajo-kit-auth adds authentication and authorization to an Ajo Kit application: cookie sessions, CSRF protection, route guards, bearer tokens with abilities, teams, invitations, passkeys, password reset and email verification. It keeps users, sessions, tokens and the rest in the application’s SQLite database through Kysely, and ships its own migrations.

Each piece is a plain function you call from handlers and wares.ts files. Nothing runs until you register the middleware or call an API, so an application can adopt sessions first and add tokens, teams or passkeys later. This guide walks through each piece; the package README lists every function and option.

Install

Terminal
pnpm add ajo-kit-auth@0.7.1

The package needs ajo-kit ^0.5.0 as a peer dependency and Node 22.18 or newer for development. Password hashing depends on argon2, which has a native build step. Allow it next to the builds Kit needs:

pnpm-workspace.yaml
allowBuilds:
  argon2: true
  better-sqlite3: true
  esbuild: true

The package is marked server-only, so Kit’s Vite plugin blocks importing it from client code. Browser code that needs ability checks imports them from ajo-kit-auth/ability instead.

Set up

  1. Include the auth tables in your database type. Auth describes every table the package owns; extend it with your own. The rest of this module follows the Database guide.

    src/database.ts
    import { db as database, type Generated } from 'ajo-kit/database'
    import type { Auth } from 'ajo-kit-auth'
    
    interface Notes {
      id: Generated<number>
      user: number
      text: string
      created: Generated<string>
    }
    
    export interface Database extends Auth {
      notes: Notes
    }
    
    export const db = () => database<Database>()
  2. Register the two root middlewares. wares.session() resolves req.user; wares.csrf rejects unsafe cookie-authenticated requests from other origins. The package queries the application’s shared connection, db() from ajo-kit/database, so there is nothing to configure.

    src/wares.ts
    import type { Middleware } from 'ajo-kit'
    import { wares } from 'ajo-kit-auth'
    
    export default [wares.session(), wares.csrf] satisfies Middleware[]
  3. Run the migrations. The package declares kit.migrations, so kit migrate discovers them next to your own and creates the auth, passkey, team and invitation tables.

    Terminal
    pnpm kit migrate up
  4. Seed the roles your application uses. The package reads the roles table (a name and a JSON array of abilities) and the members table that assigns them, but never creates roles itself.

    db/seeds/roles.ts
    import type { Kysely } from 'ajo-kit/database'
    
    export async function seed(db: Kysely<any>) {
      await db.insertInto('roles')
        .values([
          { name: 'admin', abilities: JSON.stringify(['*']) },
          { name: 'editor', abilities: JSON.stringify(['notes:*']) },
        ])
        .onConflict(conflict => conflict.column('name').doNothing())
        .execute()
    }
  5. Set APP_SECRET. It signs email verification links. Development runs without it on a built-in placeholder. The package declares it required in kit.engine, so the engine refuses to start without it, and in production (NODE_ENV=production) every operation that needs the secret throws when it is missing, shorter than 32 characters or a sample placeholder.

    .env
    APP_URL=http://localhost:5173
    APP_SECRET=<32+ random characters from your secret manager>

For non-local production, set APP_URL to the public origin used in generated links. When the host supplies a managed origins manifest, APP_URL must be an exact HTTPS origin listed there, and form checks use the current request origin through requestOrigin(req) from ajo-kit.

Sessions and cookies

A sign-in action checks the password, creates a session and writes its cookie. session.create() returns the plaintext credential for the cookie; the database stores only its SHA-256 hash.

src/login/handler.ts
import { Denied, Failure, ip, type Request, type Response } from 'ajo-kit'
import { cookie, limit, password, session } from 'ajo-kit-auth'
import { email, maxLength, object, parse, pipe, string, toLowerCase, trim } from 'ajo-kit/validate'
import { db } from '../database'

const Login = object({
  email: pipe(string(), trim(), toLowerCase(), email(), maxLength(254)),
  password: pipe(string(), maxLength(128)),
})

// Verifying against a real hash when no account matches keeps the timing uniform.
const dummy = await password.hash('not-a-real-password')

export const actions = {
  default: async (req: Request, res: Response) => {
    const input = parse(Login, req.body)
    const key = `login:${ip(req)}:${input.email}`
    if (!limit.hit(key)) throw new Failure(429, 'Too many attempts. Try again in a minute.')

    const user = await db().selectFrom('users').select(['id', 'password'])
      .where('email', '=', input.email).executeTakeFirst()
    const valid = await password.verify(input.password, user?.password ?? dummy)
    if (!user?.password || !valid) throw new Denied('Email or password is incorrect')

    limit.clear(key)
    const id = await session.create(user.id, false, ip(req), req.headers['user-agent'])
    cookie.write(res, id)
    return { redirect: '/notes' }
  },
}

To sign out, pass the value from cookie.read(req) to session.remove() and call cookie.clear(res). A session ends at an idle timeout as well as at its absolute lifetime, and over HTTPS the cookie is named __Host-session, so a sibling subdomain cannot shadow it. cookie.read() rejects a header that carries the session cookie twice.

After wares.session(), req.user holds the account with its role names and merged abilities, and req.session holds the stored (hashed) session id. The user is loaded fresh from the database on every request, so a removed role takes effect on the next one.

CSRF protection

wares.csrf decides per request:

  • Requests authenticated by a bearer token pass. So do GET, HEAD and OPTIONS.
  • Unauthenticated requests under /api/* pass.
  • Every other request, including route actions such as sign-in and registration forms, needs proof or fails with 403 Invalid CSRF token.

The proof is the browser’s own: the Origin header must be exactly the current request origin. When it is present it decides alone; Referer is consulted only when Origin is absent. A request with neither header is refused, and Origin: null never matches. Browsers send Origin with form posts and fetch calls, so forms and action() calls from your own pages pass without extra code.

On a managed App with several origins, proof must match the origin of the current request. A form on one alias does not authorize a request to another alias of the same App.

Guards

Guards are middleware for wares.ts files, or functions you call inside loaders, actions and API handlers. Failures throw Kit errors: Denied is a 401 and Forbidden a 403. Two functions check authority, and the difference matters once tokens and teams appear:

  • authorize(req, ...abilities) is the global check: the account’s roles, and the token’s abilities when a bearer token authenticated the request. Without abilities it checks only that someone is signed in.
  • admit(req, subject, ...abilities) checks one subject: global abilities plus the user’s team grants for that subject. A scoped token passes only for its own subject.

A branch-level wares.ts protects every route beneath it with protect(), and loaders still call authorize(req) so their data never depends on the redirect alone.

src/notes/wares.ts
import { protect } from 'ajo-kit-auth'

export default [protect('/login')]
src/notes/handler.ts
import type { Request } from 'ajo-kit'
import { authorize } from 'ajo-kit-auth'
import { db } from '../database'

export async function page(req: Request) {
  authorize(req)
  const notes = await db().selectFrom('notes').select(['id', 'text'])
    .where('user', '=', req.user!.id).execute()
  return { notes }
}

Bearer tokens

API tokens let scripts and other programs call /api/* routes with an Authorization: Bearer header. On those routes an explicit bearer token takes precedence over a session cookie; when the token is invalid, the request stays unauthenticated and the cookie is not consulted. Route actions always use cookie sessions.

src/settings/handler.ts
import type { Request } from 'ajo-kit'
import { authorize, token } from 'ajo-kit-auth'

export const actions = {
  token: async (req: Request) => {
    authorize(req)
    const plain = await token.create(req.user!.id, 'Import script', ['notes:write'], {
      subject: 'notebook:42',
      ttl: 30 * 24 * 60 * 60 * 1000,
    })
    return { token: plain } // Shown once; only its hash is stored.
  },
}
src/notebooks/[id]/handler.ts
import type { Request, Response } from 'ajo-kit'
import { send } from 'ajo-kit/server'
import { admit } from 'ajo-kit-auth'

// POST /api/notebooks/:id
export default {
  async post(req: Request, res: Response) {
    await admit(req, `notebook:${req.params.id}`, 'notes:write')
    // Store the imported note…
    send(res, 201, { ok: true })
  },
}
  • Abilities. * grants everything, notes:* every ability of the notes resource, and anything else matches exactly. Prefer narrow grants such as notes:write.
  • Subjects. Exact, opaque strings your application defines, with no wildcard or prefix matching. A scoped token can never satisfy authorize() with abilities; use admit().
  • Every request checks the account’s current authority as well as the token’s abilities, so issuing a token never freezes authority the account later loses.

Roles and teams

Global authority comes from roles assigned in members. Teams are subject-scoped authorization groups, not tenants: they have no settings, request context, resource ownership or data isolation. A teammate holds a role from the same roles catalog. A claim records that a team holds a subject, an opaque string your application defines. Global grants apply everywhere; on top, for one subject, a user gains the abilities of every role they hold in every team that claims it.

TypeScript
import { admit, team } from 'ajo-kit-auth'

const id = await team.create('Field notes')
await team.join(id, userId, editorRoleId) // a roles.id; joining again changes the role
await team.claim(id, 'notebook:42')       // idempotent

// Later, in a handler for that notebook:
await admit(req, 'notebook:42', 'notes:write')

team.remove(id) revokes the team’s pending invitations before deleting it.

Invitations

TypeScript
import { invite, password } from 'ajo-kit-auth'

const plain = await invite.create({ role: 'editor', team: teamId, email: 'ana@example.com', inviter: userId })
// Send a link that carries plain; it is returned only once.

const pending = await invite.get(plain) // { role, name, email, team, user } or null
const account = await invite.accept(plain, { passwordHash: await password.hash(newPassword) })

An invitation names a role, and optionally a team, and accept() creates the account atomically. An email binds acceptance to that address; only then, with a password, is the new account marked verified. Without one, the person accepting supplies the address.

Passkeys

The package implements WebAuthn itself for attestation: 'none', the format mainstream passkey providers emit. A passkey replaces exactly one step, proving the person is who they claim; the caller then creates a session as it would after password.verify.

src/passkeys/handler.ts
import { Denied, ip, type Request, type Response } from 'ajo-kit'
import { authorize, cookie, passkey, session } from 'ajo-kit-auth'

// Once, at startup. Never derived from request headers.
passkey.configure({ rpId: 'example.com', origins: ['https://example.com'] })

export const actions = {
  // Registration: a signed-in person adds a passkey in two requests.
  options: async (req: Request) => {
    authorize(req)
    return passkey.registration({ id: req.user!.id, name: req.user!.email })
  },
  register: async (req: Request) => {
    authorize(req)
    return { id: await passkey.register(req.user!.id, req.body) }
  },

  // Authentication: ask for a challenge, then answer it.
  challenge: async () => passkey.authentication(),
  signin: async (req: Request, res: Response) => {
    const user = await passkey.authenticate(req.body).catch(() => null)
    if (user === null) throw new Denied('Passkey sign-in failed')
    cookie.write(res, await session.create(user, false, ip(req), req.headers['user-agent']))
    return { redirect: '/notes' }
  },
}

The options carry base64url strings. Browser code converts them for navigator.credentials.create() or get() and posts back base64url fields: id, clientDataJSON, attestationObject and optional transports for registration; id, clientDataJSON, authenticatorData, signature and userHandle for authentication. Registration requires a discoverable credential, so authentication sends an empty allowCredentials list and the credential names its own account.

  • Both ceremonies require user verification, such as a PIN, a biometric or a device unlock. A key that proves only presence never signs in; its owner enrolls one that can verify.
  • Client data must come from one of the configured origins exactly, and challenges are single-use.
  • Failed ceremonies throw passkey.Malformed. Treat every failure the same way, as the example does.

Rate limits and confirmation

limit.hit(key) records one attempt and returns false once the key has spent its attempts in the window, as the sign-in example shows; limit.clear(key) resets it after a success. confirm records that the current credential re-entered its password: call confirm.stamp(req) after checking it, and put the confirmed() guard in front of a sensitive operation. Your application provides the /confirm page it redirects to.

Password reset and email verification

reset.create(user) returns a plaintext token for the email. reset.validate(token) is a read-only preview for the page that shows the form, and reset.consume(token, passwordHash) is the atomic boundary: it changes the password and revokes the user’s sessions and API tokens.

src/reset/[token]/handler.ts
import { Missing, type Request } from 'ajo-kit'
import { password, reset } from 'ajo-kit-auth'
import { minLength, object, parse, pipe, string } from 'ajo-kit/validate'

const Change = object({ password: pipe(string(), minLength(12)) })

export async function page(req: Request) {
  return { valid: (await reset.validate(req.params.token)) !== null }
}

export const actions = {
  default: async (req: Request) => {
    const input = parse(Change, req.body)
    const user = await reset.consume(req.params.token, await password.hash(input.password))
    if (user === null) throw new Missing('This link has expired')
    return { redirect: '/login' }
  },
}

verify.url(user, email, base) builds a signed link bound to the address it was minted for, and verify.validate(signature) marks the account verified.

TypeScript
import { origin } from 'ajo-kit'
import { verify } from 'ajo-kit-auth'
import { deliver } from 'ajo-kit-mail'

// Inside an action, after authorize(req):
const { id, email } = req.user!
const outcome = await deliver({
  to: email,
  kind: 'verify',
  subject: 'Verify your email',
  text: `Confirm this address: ${verify.url(id, email, origin(req))}`,
})
if (!outcome.ok) throw outcome.error

Typing req.user

To type the extra fields on req.user, augment Kit’s User interface with the package’s selected user row:

src/user.d.ts
import type { User as Account } from 'ajo-kit-auth'

declare module 'ajo-kit' {
  interface User extends Pick<Account, 'name' | 'email' | 'verified'> {}
}

Full reference: ajo-kit packages/ajo-kit-auth/README.md