🚨 Shai-Hulud Strikes Again:More than 500 packages and 700+ versions compromised.Technical Analysis →
Socket
Book a DemoInstallSign in
Socket

@travetto/auth-web

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@travetto/auth-web

Web authentication integration support for the Travetto framework

latest
Source
npmnpm
Version
6.0.3
Version published
Maintainers
1
Created
Source

Web Auth

Web authentication integration support for the Travetto framework

Install: @travetto/auth-web

npm install @travetto/auth-web

# or

yarn add @travetto/auth-web

This is a primary integration for the Authentication module with the Web API module.

The integration with the Web API module touches multiple levels. Primarily:

  • Authenticating
  • Maintaining Auth Context
  • Endpoint Decoration
  • Multi-Step Login

Authenticating

Every external framework integration relies upon the Authenticator contract. This contract defines the boundaries between both frameworks and what is needed to pass between. As stated elsewhere, the goal is to be as flexible as possible, and so the contract is as minimal as possible:

Code: Structure for the Identity Source

import { AnyMap } from '@travetto/runtime';
import { Principal } from './principal.ts';

/**
 * Represents the general shape of additional login context, usually across multiple calls
 *
 * @concrete
 */
export interface AuthenticatorState extends AnyMap { }

/**
 * Supports validation payload of type T into an authenticated principal
 *
 * @concrete
 */
export interface Authenticator<T = unknown, C = unknown, P extends Principal = Principal> {
  /**
   * Retrieve the authenticator state for the given request
   */
  getState?(context?: C): Promise<AuthenticatorState | undefined> | AuthenticatorState | undefined;

  /**
   * Verify the payload, ensuring the payload is correctly identified.
   *
   * @returns Valid principal if authenticated
   * @returns undefined if authentication is valid, but incomplete (multi-step)
   * @throws AppError if authentication fails
   */
  authenticate(payload: T, context?: C): Promise<P | undefined> | P | undefined;
}

The only required method to be defined is the authenticate method. This takes in a pre-principal payload and a filter context with a WebRequest, and is responsible for:

  • Returning an Principal if authentication was successful
  • Throwing an error if it failed
  • Returning undefined if the authentication is multi-staged and has not completed yet

A sample auth provider would look like:

Code: Sample Identity Source

import { AuthenticationError, Authenticator } from '@travetto/auth';

type User = { username: string, password: string };

export class SimpleAuthenticator implements Authenticator<User> {
  async authenticate({ username, password }: User) {
    if (username === 'test' && password === 'test') {
      return {
        id: 'test',
        source: 'simple',
        permissions: [],
        details: {
          username: 'test'
        }
      };
    } else {
      throw new AuthenticationError('Invalid credentials');
    }
  }
}

The provider must be registered with a custom symbol to be used within the framework. At startup, all registered Authenticator's are collected and stored for reference at runtime, via symbol. For example:

Code: Potential Facebook provider

import { InjectableFactory } from '@travetto/di';

import { SimpleAuthenticator } from './source.ts';

export const FbAuthSymbol = Symbol.for('auth-facebook');

export class AppConfig {
  @InjectableFactory(FbAuthSymbol)
  static facebookIdentity() {
    return new SimpleAuthenticator();
  }
}

The symbol FB_AUTH is what will be used to reference providers at runtime. This was chosen, over class references due to the fact that most providers will not be defined via a new class, but via an @InjectableFactory method.

Maintaining Auth Context

The AuthContextInterceptor acts as the bridge between the Authentication and Web API modules. It serves to take an authenticated principal (via the WebRequest/WebResponse) and integrate it into the AuthContext. Leveraging WebAuthConfig's configuration allows for basic control of how the principal is encoded and decoded, primarily with the choice between using a header or a cookie, and which header, or cookie value is specifically referenced. Additionally, the encoding process allows for auto-renewing of the token (on by default). The information is encoded into the JWT appropriately, and when encoding using cookies, is also set as the expiry time for the cookie.

Note for Cookie Use: The automatic renewal, update, seamless receipt and transmission of the Principal cookie act as a light-weight session. Generally the goal is to keep the token as small as possible, but for small amounts of data, this pattern proves to be fairly sufficient at maintaining a decentralized state.

The PrincipalCodec contract is the primary interface for reading and writing Principal data out of the WebRequest. This contract is flexible by design, allowing for all sorts of usage. JWTPrincipalCodec is the default PrincipalCodec, leveraging JWTs for encoding/decoding the principal information.

Code: JWTPrincipalCodec

import { createVerifier, create, Jwt, Verifier, SupportedAlgorithms } from 'njwt';

import { AuthContext, AuthenticationError, AuthToken, Principal } from '@travetto/auth';
import { Injectable, Inject } from '@travetto/di';
import { WebResponse, WebRequest, WebAsyncContext, CookieJar } from '@travetto/web';
import { AppError, castTo, TimeUtil } from '@travetto/runtime';

import { CommonPrincipalCodecSymbol, PrincipalCodec } from './types.ts';
import { WebAuthConfig } from './config.ts';

/**
 * JWT Principal codec
 */
@Injectable(CommonPrincipalCodecSymbol)
export class JWTPrincipalCodec implements PrincipalCodec {

  @Inject()
  config: WebAuthConfig;

  @Inject()
  authContext: AuthContext;

  @Inject()
  webAsyncContext: WebAsyncContext;

  #verifier: Verifier;
  #algorithm: SupportedAlgorithms = 'HS256';

  postConstruct(): void {
    this.#verifier = createVerifier()
      .setSigningAlgorithm(this.#algorithm)
      .withKeyResolver((kid, cb) => {
        const rec = this.config.keyMap[kid];
        return cb(rec ? null : new AuthenticationError('Invalid'), rec.key);
      });
  }

  async verify(token: string): Promise<Principal> {
    try {
      const jwt: Jwt & { body: { core: Principal } } = await new Promise((res, rej) =>
        this.#verifier.verify(token, (err, v) => err ? rej(err) : res(castTo(v)))
      );
      return jwt.body.core;
    } catch (err) {
      if (err instanceof Error && err.name.startsWith('Jwt')) {
        throw new AuthenticationError(err.message, { category: 'permissions' });
      }
      throw err;
    }
  }

  token(request: WebRequest): AuthToken | undefined {
    const value = (this.config.mode === 'header') ?
      request.headers.getWithPrefix(this.config.header, this.config.headerPrefix) :
      this.webAsyncContext.getValue(CookieJar).get(this.config.cookie, { signed: false });
    return value ? { type: 'jwt', value } : undefined;
  }

  async decode(request: WebRequest): Promise<Principal | undefined> {
    const token = this.token(request);
    return token ? await this.verify(token.value) : undefined;
  }

  async create(value: Principal, keyId: string = 'default'): Promise<string> {
    const keyRec = this.config.keyMap[keyId];
    if (!keyRec) {
      throw new AppError('Requested unknown key for signing');
    }
    const jwt = create({}, '-')
      .setExpiration(value.expiresAt!)
      .setIssuedAt(TimeUtil.asSeconds(value.issuedAt!))
      .setClaim('core', castTo({ ...value }))
      .setIssuer(value.issuer!)
      .setJti(value.sessionId!)
      .setSubject(value.id)
      .setHeader('kid', keyRec.id)
      .setSigningKey(keyRec.key)
      .setSigningAlgorithm(this.#algorithm);
    return jwt.toString();
  }

  async encode(response: WebResponse, data: Principal | undefined): Promise<WebResponse> {
    const token = data ? await this.create(data) : undefined;
    const { header, headerPrefix, cookie } = this.config;
    if (this.config.mode === 'header') {
      response.headers.setWithPrefix(header, token, headerPrefix);
    } else {
      this.webAsyncContext.getValue(CookieJar).set({ name: cookie, value: token, signed: false, expires: data?.expiresAt });
    }
    return response;
  }
}

As you can see, the encode token just creates a JWT based on the principal provided, and decoding verifies the token, and returns the principal.

A trivial/sample custom PrincipalCodec can be seen here:

Code: Custom Principal Codec

import { Principal } from '@travetto/auth';
import { PrincipalCodec } from '@travetto/auth-web';
import { Injectable } from '@travetto/di';
import { BinaryUtil } from '@travetto/runtime';
import { WebResponse, WebRequest } from '@travetto/web';

@Injectable()
export class CustomCodec implements PrincipalCodec {
  secret: string;

  decode(request: WebRequest): Promise<Principal | undefined> | Principal | undefined {
    const [userId, sig] = request.headers.get('USER_ID')?.split(':') ?? [];
    if (userId && sig === BinaryUtil.hash(userId + this.secret)) {
      let p: Principal | undefined;
      // Lookup user from db, remote system, etc.,
      return p;
    }
    return;
  }
  encode(response: WebResponse, data: Principal | undefined): WebResponse {
    if (data) {
      response.headers.set('USER_ID', `${data.id}:${BinaryUtil.hash(data.id + this.secret)}`);
    }
    return response;
  }
}

This implementation is not suitable for production, but shows the general pattern needed to integrate with any principal source.

Endpoint Decoration

@Login integrates with middleware that will authenticate the user as defined by the specified providers, or throw an error if authentication is unsuccessful.

@Logout integrates with middleware that will automatically deauthenticate a user, throw an error if the user is unauthenticated.

Code: Using provider with endpoints

import { Controller, Get, ContextParam, WebResponse } from '@travetto/web';
import { Login, Authenticated, Logout } from '@travetto/auth-web';
import { Principal } from '@travetto/auth';

import { FbAuthSymbol } from './facebook.ts';

@Controller('/auth')
export class SampleAuth {

  @ContextParam()
  user: Principal;

  @Get('/simple')
  @Login(FbAuthSymbol)
  async simpleLogin() {
    return WebResponse.redirect('/auth/self');
  }

  @Get('/self')
  @Authenticated()
  async getSelf() {
    return this.user;
  }

  @Get('/logout')
  @Logout()
  async logout() {
    return WebResponse.redirect('/auth/self');
  }
}

@Authenticated and @Unauthenticated will simply enforce whether or not a user is logged in and throw the appropriate error messages as needed. Additionally, the Principal is accessible as a resource that can be exposed as a @ContextParam on an @Injectable class.

Multi-Step Login

When authenticating, with a multi-step process, it is useful to share information between steps. The authenticatorState of AuthContext field is intended to be a location in which that information is persisted. Currently only passport support is included, when dealing with multi-step logins. This information can also be injected into a web endpoint method, using the AuthenticatorState type;

Keywords

authentication

FAQs

Package last updated on 07 Oct 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts