# @travetto/auth-rest-jwt

> Rest authentication JWT integration support for the Travetto framework

Latest version **5.1.0** (published 2025-01-26) · MIT license · 0 weekly downloads

## Install

```sh
npm install @travetto/auth-rest-jwt
pnpm add @travetto/auth-rest-jwt
yarn add @travetto/auth-rest-jwt
bun add @travetto/auth-rest-jwt
```

## Health

**Score 40/100 (D)** — status: stable.

Positive: no vulnerabilities; high maintenance score.

Warnings: low downloads; no types; no esm support.

Negative: stale.

## Facts

| | |
|---|---|
| Version | 5.1.0 |
| Published | 2025-01-26 |
| First published | 2022-09-05 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 6 |
| Unpacked size | 11.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 23 |
| Author | Travetto Framework |
| Maintainers | arcsine |
| Keywords | authentication, jwt, rest, travetto, decorators, typescript |

## Links

- npm: https://www.npmjs.com/package/@travetto/auth-rest-jwt
- Repository: https://github.com/travetto/travetto
- Homepage: https://travetto.io
- Issues: https://github.com/travetto/travetto/issues
- npm.io page: https://npm.io/package/@travetto/auth-rest-jwt

## Dependencies (6)

- [@travetto/di](https://npm.io/package/@travetto/di.md) ^5.1.0
- [@travetto/jwt](https://npm.io/package/@travetto/jwt.md) ^5.1.0
- [@travetto/auth](https://npm.io/package/@travetto/auth.md) ^5.1.0
- [@travetto/rest](https://npm.io/package/@travetto/rest.md) ^5.1.0
- [@travetto/config](https://npm.io/package/@travetto/config.md) ^5.1.0
- [@travetto/auth-rest](https://npm.io/package/@travetto/auth-rest.md) ^5.1.0

## Alternatives

- [@pothos/plugin-authz](https://npm.io/package/@pothos/plugin-authz.md) — 12.4K weekly downloads
- [@bounded-sh/client](https://npm.io/package/@bounded-sh/client.md) — 3.2K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads
- [@nocobase/plugin-verification](https://npm.io/package/@nocobase/plugin-verification.md) — 2.0K weekly downloads
- [escher-request](https://npm.io/package/escher-request.md) — 545 weekly downloads

## Recent versions

- 5.1.0 (latest) — 2025-01-26
- 5.0.0-rc.14 (rc) — 2024-08-25
- 5.0.20 — 2025-01-16
- 5.0.19 — 2025-01-16
- 5.0.18 — 2025-01-01
- 5.0.17 — 2024-11-16
- 5.0.16 — 2024-10-26
- 5.0.15 — 2024-10-24
- 5.0.14 — 2024-10-20
- 5.0.13 — 2024-10-10
- 5.0.12 — 2024-10-06
- 5.0.11 — 2024-10-06
- 5.0.10 — 2024-10-06
- 5.0.9 — 2024-09-30
- 5.0.8 — 2024-09-29
- … 138 more at https://npm.io/package/@travetto/auth-rest-jwt/versions

## README

<!-- This file was generated by @travetto/doc and should not be modified directly -->
<!-- Please modify https://github.com/travetto/travetto/tree/main/module/auth-rest-jwt/DOC.tsx and execute "npx trv doc" to rebuild -->
# Rest Auth JWT

## Rest authentication JWT integration support for the Travetto framework

**Install: @travetto/auth-rest-jwt**
```bash
npm install @travetto/auth-rest-jwt

# or

yarn add @travetto/auth-rest-jwt
```

One of [Rest Auth](https://github.com/travetto/travetto/tree/main/module/auth-rest#readme "Rest authentication integration support for the Travetto framework")'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 [JWT](https://jwt.io/)s. This module fulfills the contract required by [Rest Auth](https://github.com/travetto/travetto/tree/main/module/auth-rest#readme "Rest authentication integration support for the Travetto framework") of being able to encode and decode a user principal, by leveraging [JWT](https://github.com/travetto/travetto/tree/main/module/jwt#readme "JSON Web Token implementation")'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](https://github.com/travetto/travetto/tree/main/module/auth-rest-jwt/src/principal-encoder.ts#L46) is exposed as a tool for allowing for converting an authenticated principal into a JWT, and back again.

**Code: JWTPrincipalEncoder**
```typescript
import { AuthContext, Principal } from '@travetto/auth';
import { PrincipalEncoder } from '@travetto/auth-rest';
import { AppError, Runtime, TimeSpan, TimeUtil } from '@travetto/runtime';
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: TimeSpan | 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 = TimeUtil.asMillis(this.maxAge);

    if (!this.signingKey && Runtime.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()
  authContext: AuthContext;

  toJwtPayload(p: Principal): Payload {
    const exp = TimeUtil.asSeconds(p.expiresAt!);
    const iat = TimeUtil.asSeconds(p.issuedAt!);
    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.authContext.authToken = { value: 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: TimeUtil.fromNow(-1, 'h') }); // Clear out cookie
    }
  }

  /**
   * Run before encoding, allowing for session extending if needed
   */
  preEncode(p: Principal): void {
    p.expiresAt ??= TimeUtil.fromNow(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 = TimeUtil.fromNow(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](https://jwt.io/) based on the principal provided, and decoding verifies the token, and returns the principal.

---
_Source: https://npm.io/package/@travetto/auth-rest-jwt · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
