Skip to content

Credentials

Turning a credential into an Identity: the built-in login and token checkers, custom checkers, IdentityStore, password hashing with scrypt, and the guest identity.

6 min read Source

A credential is proof presented by a caller. This package recognises three kinds:

Kind Comes from Read by
login Authorization: Basic base64(name:password) LoginChecker
token Authorization: Bearer … TokenChecker, JwtTokenChecker, a custom checker
guest no credential at all the guest identity

DefaultAuthenticator holds a list of checkers. For each request it asks every checker that supports(kind) in order, and the first non-null answer wins. A rejection is null, not an exception — a malformed token is a denial, never a 500.

The identity model

interface Identity {
  /** stable identifier, the name rules compare against */
  name: string;
  /** grants held, already including the role prefix */
  grants: Array<string>;
  /** extra attributes, readable in a rule as identity.<name> */
  attributes?: Record<string, any>;
  /** false for the implicit guest identity */
  authenticated: boolean;
  /** when the identity was established, ms since epoch */
  issuedAt?: number;
  /** when the identity expires, ms since epoch */
  expiresAt?: number;
}

It is a plain object on purpose, so it can be put in a token and read without instantiating anything.

Helper Purpose
identityOf({name, grants, attributes}) build an authenticated identity, authenticated: true
guestIdentity(attributes?) build the anonymous identity
GUEST_IDENTITY the frozen default guest, name guest
grantForRole('EDITOR') ROLE_EDITOR, the prefix applied by inGrant
holdsGrant(identity, 'ROLE_EDITOR') membership check
isIdentityValid(identity, now?) false when expiresAt has passed

Login with a password

LoginChecker reads the name:password pair out of a Basic header and asks the IdentityStore two questions.

import {
  DefaultAuthenticator, Identity, IdentityStore, LoginChecker,
  ScryptPasswordHasher, SecurityConfiguration, identityOf
} from "@typeix/resty-security";

@Injectable()
class UsersStore implements IdentityStore {
  async find(name: string): Promise<Identity | null> {
    const user = await db.users.byName(name);
    return user === null ? null : identityOf({
      name: user.name,
      grants: user.roles,              // already including ROLE_
      attributes: {tenant: user.tenant}
    });
  }

  async passwordOf(name: string): Promise<string | null> {
    return db.users.passwordHashOf(name);
  }
}

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

IdentityStore is the only thing the package needs from the application:

interface IdentityStore {
  /** resolve an identity by name, null when unknown */
  find(name: string): Promise<Identity | null>;
  /** the stored password hash, null when unknown or passwordless */
  passwordOf(name: string): Promise<string | null>;
}

Returning null from find for a disabled account is the right way to reject it — the password is never even compared.

LoginChecker also takes an optional third argument, a dummy hash — any real hash you generated once and keep as a constant:

/** generated once at deploy time: await hasher.hash(crypto.randomUUID()) */
const DUMMY_HASH = "scrypt$16384$8$1$<salt>$<key>";

new LoginChecker(store, hasher, DUMMY_HASH);

When the name is unknown, the checker still runs a full verification against that dummy hash, so an unknown account and a wrong password take the same time. Without it, response timing reveals which names exist. It has to be a genuinely valid hash: a malformed one is rejected immediately by verify, which brings the timing difference back.

Password hashing

const hasher = new ScryptPasswordHasher();     // cost 16384 by default
const stored = await hasher.hash("secret");    // scrypt$16384$8$1$<salt>$<key>
await hasher.verify("secret", stored);         // timingSafeEqual
Option Default Notes
cost 16384 scrypt N; must be a power of two greater than 1
blockSize 8 scrypt r
parallelisation 1 scrypt p
keyLength 64 derived key length in bytes
saltLength 16 per-hash random salt, in bytes

The parameters travel inside the stored hash, so raising the cost later does not invalidate existing hashes — verification uses the parameters that were used to create it. A malformed hash is a rejected verification, not an exception.

PasswordHasher is an interface. Replacing scrypt with argon2 or bcrypt means one class, and nothing else in the package changes:

class ArgonHasher implements PasswordHasher {
  async hash(value: string): Promise<string> { … }
  async verify(value: string, stored: string): Promise<boolean> { … }
}

Bearer tokens

TokenChecker takes a verifier function, so any token format works — an opaque database token, an HMAC, a JWT verified by a library of your choice:

const authenticator = new DefaultAuthenticator()
  .add(new TokenChecker(async token => {
    const session = await db.sessions.byToken(token);
    return session === null ? null : identityOf({name: session.user, grants: session.roles});
  }));

The Authorization header and its Bearer prefix are read by the chain, not by the checker, so the checker only sees the token itself. Both are configurable when the API uses different conventions:

@SecurityConfiguration({
  tokenHeader: "x-api-token",
  tokenPrefix: "Token ",
  authenticator: …,
  guards: …
})

Several kinds at once

const authenticator = new DefaultAuthenticator()
  .add(new LoginChecker(usersStore, new ScryptPasswordHasher()))   // kind "login"
  .add(new TokenChecker(resolveApiToken))                          // kind "token"
  .add(new TokenChecker(resolveServiceToken));                     // second token source

Order matters only between checkers that support the same kind: the first non-null answer wins, so put the cheapest or most specific one first.

A custom checker

Implement CredentialChecker when the credential is not a bearer token or a password — an API key in a custom header, a signed request, a device certificate:

import {CredentialChecker, Identity, identityOf} from "@typeix/resty-security";

class ApiKeyChecker implements CredentialChecker {
  constructor(private readonly keys: Map<string, Array<string>>) {
  }

  supports(kind: string): boolean {
    return kind === "token";
  }

  async check(value: string): Promise<Identity | null> {
    const grants = this.keys.get(value);
    return grants === undefined ? null : identityOf({name: `key:${value.slice(0, 6)}`, grants});
  }
}

A checker that answers for a header the chain does not read needs the chain to see it — either configure tokenHeader / tokenPrefix, or read the header in a rule instead of resolving an identity at all (see Rules).

The guest identity

An anonymous caller still has an identity, so rules never deal with null:

Property Value
name guest
grants []
authenticated false

guestFactory lets you attach request data to it, which makes rules like "any caller from this tenant" expressible on open routes:

@SecurityConfiguration({
  guestFactory: request => guestIdentity({tenant: request.headers["x-tenant"]}),
  guards: guards => guards
    .match("/public/**", "identity.tenant == 'acme'")
    .anyRequest("identified()")
})

A guest factory cannot authenticate anyone: the resulting identity still has authenticated: false, so identified() keeps answering false for it.

Next