npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@travetto/auth-rest-jwt

v4.0.7

Published

Rest authentication JWT integration support for the Travetto framework

Downloads

171

Readme

Rest Auth JWT

Rest authentication JWT integration support for the Travetto framework

Install: @travetto/auth-rest-jwt

npm install @travetto/auth-rest-jwt

# or

yarn add @travetto/auth-rest-jwt

One of Rest Auth's main responsibilities is being able to send and receive authentication/authorization information from the client. This data can be encoded in many different forms, and this module provides the ability to encode into and decode from JWTs. This module fulfills the contract required by Rest Auth of being able to encode and decode a user principal, by leveraging JWT's token generation features.

The token can be encoded as a cookie or as a header depending on configuration. Additionally, the encoding process allows for auto-renewing of the token if that is desired. When encoding as a cookie, this becomes a seamless experience, and can be understood as a light-weight session.

The JWTPrincipalEncoder is exposed as a tool for allowing for converting an authenticated principal into a JWT, and back again.

Code: JWTPrincipalEncoder

import { Principal } from '@travetto/auth';
import { AuthService, PrincipalEncoder } from '@travetto/auth-rest';
import { AppError, Env, TimeUtil } from '@travetto/base';
import { Config } from '@travetto/config';
import { Inject, Injectable } from '@travetto/di';
import { FilterContext } from '@travetto/rest';
import { JWTUtil, Payload } from '@travetto/jwt';
import { Ignore } from '@travetto/schema';

@Config('rest.auth.jwt')
export class RestJWTConfig {
  mode: 'cookie' | 'header' | 'all' = 'header';
  header = 'Authorization';
  cookie = 'trv.auth';
  signingKey?: string;
  headerPrefix = 'Bearer';
  maxAge: string | number = '1h';
  rollingRenew: boolean = false;

  @Ignore()
  maxAgeMs: number;

  get cookieMode(): boolean {
    return this.mode === 'cookie' || this.mode === 'all';
  }

  get headerMode(): boolean {
    return this.mode === 'header' || this.mode === 'all';
  }

  postConstruct(): void {

    this.maxAgeMs = typeof this.maxAge === 'string' ? TimeUtil.timeToMs(this.maxAge as '1y') : this.maxAge;

    if (!this.signingKey) {
      if (Env.production) {
        throw new AppError('The default signing key is only valid for development use, please specify a config value at rest.auth.jwt.signingKey');
      }
      this.signingKey = 'dummy';
    }
  }
}

/**
 * Principal encoder via JWT
 */
@Injectable()
export class JWTPrincipalEncoder implements PrincipalEncoder {

  @Inject()
  config: RestJWTConfig;

  @Inject()
  auth: AuthService;

  toJwtPayload(p: Principal): Payload {
    const exp = Math.trunc(p.expiresAt!.getTime() / 1000);
    const iat = Math.trunc(p.issuedAt!.getTime() / 1000);
    return {
      auth: {
        ...p,
      },
      exp,
      iat,
      iss: p.issuer,
      sub: p.id,
    };
  }

  /**
   * Get token for principal
   */
  async getToken(p: Principal): Promise<string> {
    return await JWTUtil.create(this.toJwtPayload(p), { key: this.config.signingKey });
  }

  /**
   * Rewrite token with new permissions
   */
  updateTokenPermissions(token: string, permissions: string[]): Promise<string> {
    return JWTUtil.rewrite<{ auth: Principal }>(
      token,
      p => ({
        ...p,
        auth: {
          ...p.auth,
          permissions
        }
      }),
      { key: this.config.signingKey }
    );
  }

  /**
   * Verify token to principal
   * @param token
   */
  async verifyToken(token: string, setActive = false): Promise<Principal> {
    const res = (await JWTUtil.verify<{ auth: Principal }>(token, { key: this.config.signingKey })).auth;
    if (setActive) {
      this.auth.setAuthenticationToken({ token, type: 'jwt' });
    }
    return {
      ...res,
      expiresAt: new Date(res.expiresAt!),
      issuedAt: new Date(res.issuedAt!),
    };
  }

  /**
   * Write context
   */
  async encode({ res }: FilterContext, p: Principal | undefined): Promise<void> {
    if (p) {
      const token = await this.getToken(p);
      if (this.config.cookieMode) {
        res.cookies.set(this.config.cookie, token, { expires: p.expiresAt });
      }
      if (this.config.headerMode) {
        res.setHeader(this.config.header, [this.config.headerPrefix, token].join(' ').trimStart());
      }
    } else if (this.config.cookieMode) {
      res.cookies.set(this.config.cookie, '', { expires: new Date(Date.now() - 1000 * 60 * 60) }); // Clear out cookie
    }
  }

  /**
   * Run before encoding, allowing for session extending if needed
   */
  preEncode(p: Principal): void {
    p.expiresAt ??= new Date(Date.now() + this.config.maxAgeMs);
    p.issuedAt ??= new Date();

    if (this.config.rollingRenew) {
      const end = p.expiresAt.getTime();
      const midPoint = end - this.config.maxAgeMs / 2;
      if (Date.now() > midPoint) { // If we are past the half way mark, renew the token
        p.issuedAt = new Date();
        p.expiresAt = new Date(Date.now() + this.config.maxAgeMs); // This will trigger a re-send
      }
    }
  }

  /**
   * Read JWT from request
   */
  async decode({ req }: FilterContext): Promise<Principal | undefined> {
    let token: string | undefined = undefined;
    if (this.config.cookieMode) {
      token ??= req.cookies.get(this.config.cookie);
    }
    if (this.config.headerMode) {
      const header = req.headerFirst(this.config.header);
      if (header?.startsWith(this.config.headerPrefix)) {
        token ??= header.replace(this.config.headerPrefix, '').trim();
      }
    }

    if (token) {
      return await this.verifyToken(token, true);
    }
  }
}

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.