Skip to content

typeix/resty-security

The @typeix/resty-security package: identity and access rules for resty — a single guard chain over every route, declarative authenticators resolved by the injector, password login, and a dependency-free JWT verifier.

7 min read Source

Identity and access rules for the resty framework.

One interceptor covers every route — including the ones registered by @typeix/resty-swagger, @typeix/resty-graphql and @typeix/resty-ws — so there is no per-router wiring and no route that quietly escapes the rules. Rules are declared as small expressions, parsed once at boot, so a typo fails at startup instead of letting a request through.

Release

@typeix/resty-security ships with Typeix 9.2.0.

Requirements

  • Node.js ^26.0.0
  • @typeix/resty ^9.2.0

Install

npm i @typeix/resty-security

There are no runtime dependencies. Password hashing uses node:crypto scrypt and the JWT adapter uses node:crypto only, so nothing is pulled in for either.

Quick start

import {createServer} from "http";
import {Controller, GET, Injectable, pipeServer, RootModule} from "@typeix/resty";
import {
  DefaultAuthenticator, Guard, Identity, IdentityStore, LoginChecker,
  ScryptPasswordHasher, SecurityConfiguration, identityOf
} from "@typeix/resty-security";

@Injectable()
class UsersStore implements IdentityStore {
  async find(name: string): Promise<Identity | null> {
    return name === "ada" ? identityOf({name, grants: ["ROLE_EDITOR"]}) : null;
  }

  async passwordOf(name: string): Promise<string | null> {
    return name === "ada" ? await new ScryptPasswordHasher().hash("secret") : null;
  }
}

@Controller({path: "/articles"})
class ArticlesController {
  @GET()
  list(): object {
    return {articles: []};
  }

  @GET("/draft")
  @Guard("inGrant('EDITOR')")
  draft(): object {
    return {draft: true};
  }
}

@SecurityConfiguration({
  authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
    .add(new LoginChecker(store, new ScryptPasswordHasher())),
  guards: guards => guards
    .match("/health", "allow()")
    .anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {
}

async function bootstrap() {
  const server = createServer();
  await pipeServer(server, Application);
  server.listen(3000);
}

bootstrap();
curl -i http://localhost:3000/articles                                # 401 Unauthorized
curl -i -u ada:secret http://localhost:3000/articles                  # 200
curl -i -u ada:secret http://localhost:3000/articles/draft            # 200, holds ROLE_EDITOR

pipeServer(server, Application) is unchanged: the decorator publishes the chain through metadata, and the server reads it. Nothing about the application's bootstrap has to know that security exists.

How it works

http request
  │
  ├─ GuardChain                       application-wide interceptor
  │    ├─ resolve the credential  →  Identity | guest
  │    ├─ rule list, first match wins
  │    └─ deny → 401 / 403 and the handler never runs
  │
  ├─ controller and method interceptors
  │    ├─ @Guard         rule before the handler
  │    └─ @GuardResult   rule on the handler's return value
  │
  └─ handler

Three properties follow from that shape, and they are the reason to prefer it over per-route middleware:

  • Deny by default. A request that matches no rule is denied. A route added later, without a rule, is protected rather than exposed.
  • Fail at boot. unknown rule function "hasRole" is thrown when the class is defined, not when a request arrives.
  • One decision point. The same Identity object reaches the rules, the handler (@CurrentIdentity()), and any request-scoped service (IDENTITY_CONTEXT).

Declaring rules

@SecurityConfiguration({
  guards: guards => guards
    .match("/admin/public", "allow()")                          // most specific first
    .match("/admin/**", "inGrant('ADMIN')")
    .match("/articles", "may('article:write')", ["POST"])       // one method only
    .match("/articles/<id>", "method != 'DELETE' or may('article:delete')")
    .anyRequest("identified()")                                 // fallback, must be last
})
Method Purpose
match(patterns, rule, methods?) add a rule for one pattern or a list of patterns, optionally limited to http methods
anyRequest(rule) fallback for everything not matched above; without it, unmatched is denied

Rules are evaluated in declaration order and the first match wins. There are exactly two ways to get this wrong, and both are boot errors: declaring match after anyRequest (it could never match) and calling anyRequest twice.

The rule language is deliberately small — allow(), deny(), identified(), guest(), inGrant('EDITOR'), may('article:write'), comparisons against identity.*, #param, header('x'), query('q'), path and method, combined with and / or / not. See Rules for the complete reference.

The authenticator

authenticator accepts a provider or a factory — never a pre-resolved instance, so the injector always owns the object:

// factory: arguments come from shared_providers, in declaration order
@SecurityConfiguration({
  authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
    .add(new LoginChecker(store, new ScryptPasswordHasher())),
  guards: guards => guards.anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {}
// provider: the token is the provider's own `provide`
@SecurityConfiguration({
  authenticator: {
    provide: DefaultAuthenticator,
    useFactory: () => new DefaultAuthenticator([new TokenChecker(verifyOpaqueToken)])
  },
  guards: guards => guards.anyRequest("identified()")
})

DefaultAuthenticator is @Injectable() and its constructor is unchanged, so new DefaultAuthenticator([...]) keeps working for a hand-built authenticator, while the DI form registers checkers with .add() on the injector-owned instance. Listing the bare class in shared_providers is enough: the entry is normalized to a zero-arg factory, because useClass is the one injector path that reads design:paramtypes and the class takes a checkers array.

authenticatorToken does not exist. The provider's own provide is the token, otherwise it is DefaultAuthenticator — which is also what @Inject(DefaultAuthenticator) resolves to, so application code and the guard chain share one object.

Options

SecurityConfig — everything @SecurityConfiguration accepts:

Option Type Default Description
guards (builder: GuardBuilder) => void required the rule list
authenticator IProvider \| (...deps: any[]) => DefaultAuthenticator – credential resolution; omit it and every caller is a guest
providers Array<IProvider \| Function> [] factory arguments, in order; overrides the shared-provider order
tokenHeader string authorization header carrying a bearer token
tokenPrefix string Bearer prefix inside that header
challengeMessage string Unauthorized body message for 401
denialMessage string Forbidden body message for 403
guestFactory (request) => Identity – build the guest identity, e.g. to attach request attributes

SecurityOptions — what GuardChain takes directly, and what createGuardChain builds:

Option Type Default Description
guards GuardBuilder required the built rule list
authenticator DefaultAuthenticator – omit it and every caller is a guest
tokenHeader string authorization bearer token header
tokenPrefix string Bearer bearer prefix
loginHeader string authorization the header Basic login is read from; only available on a directly built chain
challengeMessage string Unauthorized 401 body message
denialMessage string Forbidden 403 body message
guestFactory (request) => Identity – build the guest identity

Exports

Export Kind Purpose
@SecurityConfiguration(config) decorator declares the rules and the credential source on the root module
SecurityConfig type the options above
AuthenticatorSource type IProvider \| factory
SecurityProviderFactory type the injector-aware builder returned when the authenticator is resolved at boot
createGuardChain(config, authenticator?) function build a chain for a caller-owned authenticator
createSecurityProviders(config, sharedTokens?) function what the decorator uses internally
GuardChain class the interceptor; also usable without the decorator
GuardBuilder, buildGuards rules the rule list and its builder
@Guard, @GuardResult, @Open, @CurrentIdentity decorators method rules and identity injection
DefaultAuthenticator class holds the checkers; first non-null answer wins
LoginChecker, TokenChecker classes built-in credential checkers
Identity, Grant, Credential types the identity model
identityOf, guestIdentity, GUEST_IDENTITY, grantForRole, holdsGrant, isIdentityValid functions identity helpers
IdentityStore, CredentialChecker, Authenticator types the extension points
PasswordHasher, ScryptPasswordHasher class password hashing interface and scrypt implementation
IDENTITY, IDENTITY_CONTEXT, IdentityContext tokens read the identity from a service
JwtVerifier, JwtError, JwtTokenChecker, signJwt class / function the JWT adapter

Guides

The package page is the map. Each topic has a guide:

Guide Covers
Security quick start wiring an app, the first rules, 401 vs 403
Rules patterns, order, the complete rule grammar, what a rule can read
The authenticator every declaration form, argument sources, reuse, boot errors
Credentials login, tokens, custom checkers, identity stores, password hashing
JWT verification policy, claims, issuing tokens, algorithm confusion
Method rules @Guard, @GuardResult, @Open, @CurrentIdentity
Protecting every endpoint docs, GraphQL, websockets and the request pipeline
Testing rules without a server, secured endpoints over real http

Relation to other packages

Package What it contributes
@typeix/resty ServerConfig.interceptors and APPLICATION_INTERCEPTOR_FACTORIES — the hooks the chain is published through
@typeix/resty-swagger /docs routes go through createRouteHandler, so the same chain covers them
@typeix/resty-graphql /graphql is covered too; authentication completes before query parsing
@typeix/resty-ws websocket connections do not pass through the chain; the http handshake and the controller's own injector are where access is decided

Versioning note

The public names deliberately differ from Spring Security's: GuardChain, inGrant, may, DefaultAuthenticator, @CurrentIdentity. Only Identity and Grant are shared with common vocabulary.

Renamed before the first publish, in 9.2.0 — the old spellings are not aliases and fail at boot:

Was Now
open() allow()
closed() deny()
authenticator: instance authenticator: {provide: DefaultAuthenticator, useFactory: () => instance}
authenticatorToken – (the provider's provide is the token)