Packages / Auth / Overview

Overview

Lightweight auth primitives - AuthProvider interface, AuthGuard factory, HTTP token extractors, timing-safe utilities.

@miiajs/auth is a thin layer of primitives for building authentication into MiiaJS applications. It does not ship built-in JWT, OAuth, or password logic - those are application-level concerns. Instead, it gives you three things:

  • AuthProvider - an interface describing a class that authenticates a request.
  • AuthGuard(Provider, ...more) - a guard factory that runs one or more providers.
  • HTTP utilities - token extractors, constant-time string comparison.

For JWT signing and verification, see @miiajs/jwt. For end-to-end examples, see the recipes linked below.

Installation

bun add @miiajs/auth

AuthProvider

A provider is a regular @Injectable() class that reads a request and returns the authenticated subject - or throws an HttpException.

typescript
import { Injectable, inject, UnauthorizedException, type RequestContext } from '@miiajs/core'
import { fromHeader, type AuthProvider } from '@miiajs/auth'
import { JwtService } from '@miiajs/jwt'
import { UsersService } from './users.service.js'

@Injectable()
export class JwtAuth implements AuthProvider {
  private jwtService = inject(JwtService)
  private usersService = inject(UsersService)
  private extract = fromHeader()

  async authenticate(ctx: RequestContext) {
    const token = this.extract(ctx)
    if (!token) throw new UnauthorizedException('Missing token')

    const payload = await this.jwtService.verify<{ sub: number }>(token).catch(() => {
      throw new UnauthorizedException('Invalid token')
    })

    const user = await this.usersService.findById(payload.sub)
    if (!user) throw new UnauthorizedException('User not found')
    return user
  }
}

Register it like any other provider. AuthGuard(JwtAuth) belongs to no module, so JwtAuth must be visible from the module of every controller that uses the guard (see Guards and modules). The usual shape is a global AuthModule that exports the provider:

typescript
@Module({
  global: true,
  imports: [UsersModule], // JwtAuth injects UsersService, which UsersModule exports
  providers: [JwtAuth],
  exports: [JwtAuth],
})
class AuthModule {}

Because AuthModule is global, UsersController sees JwtAuth without UsersModule importing AuthModule - an import that would close a cycle, since AuthModule imports UsersModule. JwtService comes from JwtModule.configure(options, { global: true }) in the root module.

AuthGuard

AuthGuard(Provider, ...more) builds a guard that tries each provider in order and assigns the first success to ctx.user. At least one provider is required.

typescript
import { AuthGuard } from '@miiajs/auth'
import { UseGuard, Controller, Get, type RequestContext } from '@miiajs/core'
import { JwtAuth } from './providers/jwt-auth.js'

@Controller('/users')
@UseGuard(AuthGuard(JwtAuth))
class UserController {
  @Get('/me')
  me(ctx: RequestContext) {
    return ctx.user
  }
}

The guard class is named after its providers, so a startup error names it AuthGuard(JwtAuth):

AuthGuard(JwtAuth) (guard of UsersController in UsersModule) injects JwtAuth (AuthModule):
  - add JwtAuth to AuthModule `exports`
  - add AuthModule to UsersModule `imports`

Multi-provider (OR)

Pass more than one provider class for fall-back authentication. The first provider that succeeds wins, and its result becomes ctx.user. If a provider throws an HttpException, the guard moves on to the next one. Any other error (TypeError, ReferenceError, etc.) is treated as a programming bug and propagates immediately - it is never silently swallowed.

typescript
@UseGuard(AuthGuard(JwtAuth, ApiKeyAuth))

If every provider throws an HttpException, the last error is rethrown.

AND semantics

Stack guards on top of each other to require multiple checks (Roles here is a parameterized guard you write yourself):

typescript
@UseGuard(AuthGuard(JwtAuth), Roles('admin'))

Skipping

@SkipGuard(AuthGuard) (referencing the factory itself) removes the auth guard from a specific route at compile time - zero runtime cost.

typescript
import { SkipGuard } from '@miiajs/core'

@Controller('/posts')
@UseGuard(AuthGuard(JwtAuth))
class PostController {
  @Get('/')
  @SkipGuard(AuthGuard)
  list() {
    return [] // public
  }
}

Naming the factory skips every guard AuthGuard(...) built on that route: the global one, the controller's, and one in @UseGuard on the same method. @SkipGuard(AuthGuard) next to @UseGuard(AuthGuard(ApiKeyAuth)) leaves the route public, not on API keys. To replace a global auth guard on one route, keep it in a constant and skip that class - each AuthGuard(...) call builds a new one, so nothing else matches it:

typescript
export const JwtGuard = AuthGuard(JwtAuth)

app.useGuard(JwtGuard)

@Controller('/webhooks')
class WebhookController {
  @Post('/')
  @SkipGuard(JwtGuard)
  @UseGuard(AuthGuard(ApiKeyAuth))
  receive(ctx: RequestContext) {
    return { received: true } // API key only
  }
}

Typing ctx.user

RequestContext does not declare user - neither @miiajs/core nor @miiajs/auth knows what your providers return. Declare it once in your project with module augmentation:

typescript
// src/types/core.d.ts
import type { User } from '../users/user.table.js'

declare module '@miiajs/core' {
  interface RequestContext {
    user?: User
  }
}

The examples on this page and in the recipes assume this declaration.

Token extractors

typescript
import { fromHeader, fromCookie, fromQuery } from '@miiajs/auth'

fromHeader()                  // Authorization: Bearer <token>
fromHeader('x-auth', '')      // X-Auth: <token>
fromCookie('access_token')    // Cookie: access_token=<...>
fromQuery('token')            // ?token=<...>

Each extractor returns (ctx: RequestContext) => string | null. Use them inside your provider's authenticate() method - they are not coupled to JWT, you can use them for API keys, session cookies, anything header- or cookie-based. fromHeader() matches the scheme case-insensitively, as HTTP defines it - bearer <token> is read too. fromCookie() returns the raw cookie value as it sits in the header - no URL-decoding, no quote stripping - unlike ctx.cookies.get(). A JWT survives that; for values written with ctx.res.cookie(), which URL-encodes them, decode it yourself.

timingSafeEqual

Constant-time string comparison - use it when comparing pre-hashed tokens, HMAC digests, or API keys without leaking which byte differs through timing side channels. Inputs of different byte length return false immediately, so compare fixed-length values such as hashes or HMAC digests.

typescript
import { timingSafeEqual } from '@miiajs/auth'

if (!timingSafeEqual(providedHash, expectedHash)) {
  throw new UnauthorizedException()
}

Not for plaintext passwords - use bcrypt.compare or argon2.verify instead.

Recipes

Complete worked examples - standalone, copy-pasteable patterns. Each recipe demonstrates the AuthProvider interface for a different credential source:

Testing

Override the AuthProvider at the DI level with TestApp.override(). Guards run unchanged - they resolve whichever provider you wired up, so an object with an authenticate() method is enough to drive any auth path. The override is typed against the provider, so authenticate() returns what the real one does - a promise of the user for an async provider:

typescript
import { TestApp } from '@miiajs/testing'
import { JwtAuth } from './providers/jwt-auth.js'

type User = Awaited<ReturnType<JwtAuth['authenticate']>>

const app = await TestApp.create(AppModule)
  .override(JwtAuth, { authenticate: async () => ({ id: 1, email: '[email protected]' }) as User })
  .compile()

const res = await app.request('GET', '/users/me')
expect(res.status).toBe(200)

await app.close()

To exercise 401/403 paths, override with an object whose authenticate() throws UnauthorizedException or ForbiddenException from @miiajs/core. The guard rethrows them unchanged.

Exports

typescript
import {
  AuthGuard,
  fromHeader,
  fromCookie,
  fromQuery,
  timingSafeEqual,
  type AuthProvider,
  type TokenExtractor,
} from '@miiajs/auth'
Edit this page on GitHub