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

@whook/authorization

v16.1.0

Published

A wrapper to provide authorization support to a Whook server

Downloads

575

Readme

@whook/authorization

A wrapper to provide authorization support to a Whook server

GitHub license

This Whook wrapper ties authentication with only two kinds of input:

  • the authorization header which allows several mechanisms to be used including custom ones (this module is using http-auth-utils under the hood). This is the recommended way to authenticate with a server.
  • the access_token defined by the RFC6750 that allows providing the token via query parameters for convenience (mostly for development purpose). Note that you can disable it by setting the DEFAULT_MECHANISM constant to an empty string.

Note that the form-encoded body parameter defined by the bearer authentication RFC is volontarily not supported since nowadays everyone uses JSON and there is no situations where one could not set the token in headers.

To use this wrapper, you'll have to create an authentication service. Here is a simple unique token based implementation (usually in src/services/authentication.ts):

import { autoService } from 'knifecycle';
import { YError } from 'yerror';
import {
  AuthenticationService,
  BaseAuthenticationData,
} from '@whook/authorization';

export type AuthenticationConfig = {
  TOKEN: string;
};

export type BearerPayload = { hash: string };
export type MyAuthenticationService = AuthenticationService<
  BearerPayload,
  BaseAuthenticationData & {
    userId: number;
  }
>;

export default autoService(initAuthentication);

async function initAuthentication({
  TOKEN,
}: AuthenticationConfig): Promise<MyAuthenticationService> {
  const authentication: MyAuthenticationService = {
    // The authentication service must have a check
    // method which take the type of authentication
    // used by the client and its parsed payload
    check: async (type, data) => {
      if (type === 'bearer') {
        if (data.hash === TOKEN) {
          // When successful, the authentication check
          // must return an object with at least a `scopes`
          // property containing an array of the actual
          // scopes the authentication check resolved to
          return {
            applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
            userId: 1,
            scope: 'admin',
          };
        }
        throw new YError('E_BAD_BEARER_TOKEN', type, data.hash);
      }
      // Of course, the service must check the auth type
      // and fail if not supported to avoid security issues
      throw new YError('E_UNEXPECTED_AUTH_TYPE', type);
    },
  };

  return authentication;
}

The properties added next to the scopes one will be passed to the wrapped handlers and an authenticated property will also be added in order for handlers to know if the client were authenticated.

Then, simply install this plugin:

npm i @whook/authorization;

Declare this module types in your src/whook.d.ts type definitions:

+ import type { WhookAuthorizationConfig } from '@whook/authorization';

// ...

declare module 'application-services' {

  // ...

  export interface AppConfig
    extends WhookBaseConfigs,
      WhookAuthorizationConfig,
      WhookSwaggerUIConfig,
      WhookCORSConfig,
      APIConfig,
  export interface AppConfig
    extends WhookBaseConfigs,
+    WhookAuthorizationConfig,
    JWTServiceConfig {}

  // ...

}

Then add the config and the errors descriptors or provide your own (usually in src/config/common/config.js):

// ...
import { DEFAULT_ERRORS_DESCRIPTORS } from '@whook/http-router';
+ import {
+   AUTHORIZATION_ERRORS_DESCRIPTORS,
+ } from '@whook/authorization';
import type { AppConfig } from 'application-services';

// ...

const CONFIG: AppConfig = {
  // ...
-   ERRORS_DESCRIPTORS: DEFAULT_ERRORS_DESCRIPTORS,
+   ERRORS_DESCRIPTORS: {
+     ...DEFAULT_ERRORS_DESCRIPTORS,
+     ...AUTHORIZATION_ERRORS_DESCRIPTORS,
+   },
+   DEFAULT_MECHANISM: 'bearer',
  // ...
};

export default CONFIG;

And finally declare this plugin in the src/index.ts file of your project:


  // ...

  $.register(
    constant('HANDLERS_WRAPPERS', [
      'wrapHandlerWithCORS',
+      'wrapHandlerWithAuthorization',
    ]),
  );

  // ...

  $.register(
    constant('WHOOK_PLUGINS', [
      ...WHOOK_DEFAULT_PLUGINS,
      '@whook/cors',
+      '@whook/authorization',
    ]),
  );

  // ...

To see a complete usage of this wrapper, you may have a look at the @whook/example project.

API

initWrapHandlerWithAuthorization(services) ⇒ Promise.<Object>

Wrap an handler to check client's authorizations.

Kind: global function
Returns: Promise.<Object> - A promise of an object containing the reshaped env vars.

| Param | Type | Description | | --- | --- | --- | | services | Object | The services ENV depends on | | [services.MECHANISMS] | Array | The list of supported auth mechanisms | | [services.DEFAULT_MECHANISM] | string | The default authentication mechanism | | services.authentication | Object | The authentication service | | services.log | Object | A logging service |

Authors

License

MIT