# @travetto/auth-rest

> Rest authentication 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
pnpm add @travetto/auth-rest
yarn add @travetto/auth-rest
bun add @travetto/auth-rest
```

## 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 | 2018-08-19 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 21.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 23 |
| Author | Travetto Framework |
| Maintainers | arcsine |
| Keywords | authentication, rest, travetto, decorators, typescript |

## Links

- npm: https://www.npmjs.com/package/@travetto/auth-rest
- 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

## Dependencies (3)

- [@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

## Alternatives

- [@clerk/clerk-expo](https://npm.io/package/@clerk/clerk-expo.md) — 133.6K weekly downloads
- [@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
- [@oxyhq/services](https://npm.io/package/@oxyhq/services.md) — 2.3K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads

## Recent versions

- 5.1.0 (latest) — 2025-01-26
- 6.0.0-rc.3 (rc) — 2025-02-04
- 2.0.0-alpha.19 (alpha) — 2021-05-05
- 1.1.0-rc.0 (next) — 2020-09-20
- 1.0.0-beta.11 (beta) — 2019-10-04
- 6.0.0-rc.2 — 2025-02-01
- 6.0.0-rc.1 — 2025-01-31
- 6.0.0-rc.0 — 2025-01-31
- 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
- … 330 more at https://npm.io/package/@travetto/auth-rest/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/DOC.tsx and execute "npx trv doc" to rebuild -->
# Rest Auth

## Rest authentication integration support for the Travetto framework

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

# or

yarn add @travetto/auth-rest
```

This is a primary integration for the [Authentication](https://github.com/travetto/travetto/tree/main/module/auth#readme "Authentication scaffolding for the Travetto framework") module.  This is another level of scaffolding allowing for compatible authentication frameworks to integrate. 

The integration with the [RESTful API](https://github.com/travetto/travetto/tree/main/module/rest#readme "Declarative api for RESTful APIs with support for the dependency injection module.") module touches multiple levels. Primarily:
   *  Patterns for auth framework integrations
   *  Route declaration
   *  Multi-Step Login

## Patterns for Integration
Every external framework integration relies upon the [Authenticator](https://github.com/travetto/travetto/tree/main/module/auth/src/types/authenticator.ts#L14) 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**
```typescript
import { AnyMap } from '@travetto/runtime';
import { Principal } from './principal';

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

/**
 * Supports validation payload of type T into an authenticated principal
 *
 * @concrete ../internal/types#AuthenticatorTarget
 */
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 [Request](https://github.com/travetto/travetto/tree/main/module/rest/src/types.ts#L31) and [Response](https://github.com/travetto/travetto/tree/main/module/rest/src/types.ts#L161), and is responsible for:
   *  Returning an [Principal](https://github.com/travetto/travetto/tree/main/module/auth/src/types/principal.ts#L8) 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**
```typescript
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](https://github.com/travetto/travetto/tree/main/module/auth/src/types/authenticator.ts#L14)'s are collected and stored for reference at runtime, via symbol. For example:

**Code: Potential Facebook provider**
```typescript
import { InjectableFactory } from '@travetto/di';

import { SimpleAuthenticator } from './source';

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

export class AppConfig {
  @InjectableFactory(FB_AUTH)
  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](https://github.com/travetto/travetto/tree/main/module/di/src/decorator.ts#L70) method.

## Route Declaration
[@Login](https://github.com/travetto/travetto/tree/main/module/auth-rest/src/decorator.ts#L13) integrates with middleware that will authenticate the user as defined by the specified providers, or throw an error if authentication is unsuccessful.

[@Logout](https://github.com/travetto/travetto/tree/main/module/auth-rest/src/decorator.ts#L45) integrates with middleware that will automatically deauthenticate a user, throw an error if the user is unauthenticated.

**Code: Using provider with routes**
```typescript
import { Controller, Get, Redirect, Request } from '@travetto/rest';
import { Login, Authenticated, Logout } from '@travetto/auth-rest';

import { FB_AUTH } from './facebook';

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

  @Get('/simple')
  @Login(FB_AUTH)
  async simpleLogin() {
    return new Redirect('/auth/self', 301);
  }

  @Get('/self')
  @Authenticated()
  async getSelf(req: Request) {
    return req.auth;
  }

  @Get('/logout')
  @Logout()
  async logout() {
    return new Redirect('/auth/self', 301);
  }
}
```

[@Authenticated](https://github.com/travetto/travetto/tree/main/module/auth-rest/src/decorator.ts#L24) and [@Unauthenticated](https://github.com/travetto/travetto/tree/main/module/auth-rest/src/decorator.ts#L35) will simply enforce whether or not a user is logged in and throw the appropriate error messages as needed. Additionally, the [Principal](https://github.com/travetto/travetto/tree/main/module/auth/src/types/principal.ts#L8) is accessible via [@Context](https://github.com/travetto/travetto/tree/main/module/rest/src/decorator/param.ts#L38) directly, without wiring in a request object, but is also accessible on the request object as [Request](https://github.com/travetto/travetto/tree/main/module/rest/src/types.ts#L31).auth.

## Multi-Step Login
When authenticating, with a multi-step process, it is useful to share information between steps.  The `authenticatorState` of [AuthContext](https://github.com/travetto/travetto/tree/main/module/auth/src/context.ts#L16) field is intended to be a location in which that information is persisted. Currently only [passport](http://passportjs.org) support is included, when dealing with multi-step logins. This information can also be injected into a rest endpoint method, using the [Authenticator](https://github.com/travetto/travetto/tree/main/module/auth/src/types/authenticator.ts#L7) type;

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